SOLVED help w/ eliminating unnecessary repetition

Mr Errorz

Member
working on a mobile project, I want a certain button to function if pressed by mouse_0 or mouse_1,
I wrote this piece of code, but there must be a better way of writing it without repeating it twice like I did.
help?

if point_in_rectangle(device_mouse_x(0),device_mouse_y(0),bbox_left,bbox_top,bbox_right,bbox_bottom)
{
if device_mouse_check_button_pressed(0,mb_left)
{
with oPlayer
{
// DO STUFF
}
}
}

else
if point_in_rectangle(device_mouse_x(1),device_mouse_y(1),bbox_left,bbox_top,bbox_right,bbox_bottom)
{
if device_mouse_check_button_pressed(1,mb_left)
{
with oPlayer
{
// DO STUFF
}
}
}
 
D

Deleted member 45063

Guest
Without checking if there are better functions you could use, use a simple for loop:
GML:
for (var i = 0; i <= 1 /* or whatever other bound you want */; i++) {
  if point_in_rectangle(device_mouse_x(i), device_mouse_y(i), bbox_left, bbox_top, bbox_right, bbox_bottom) {
    if device_mouse_check_button_pressed(i, mb_left) {
      with oPlayer {
        // DO STUFF
      }
      break; // IMPORTANT: Otherwise if both are true then the code is executed twice
    }
  }
}
 
H

Homunculus

Guest
I don't see anything really wrong with that code, at the end of the day you have to check the position and button status for both devices one way or another. You definitely want to avoid repeating the code in the with block though. You can keep the code as it is an just call a script instead of repeating it, or better, reorganise the code so that you only need to specify it once, like this for example:

GML:
var _devices = 2;

for(var _i = 0; _i < _devices; _i++)
{
  if point_in_rectangle(device_mouse_x(_i),device_mouse_y(_i),bbox_left,bbox_top,bbox_right,bbox_bottom)
  {
    if device_mouse_check_button_pressed(_i,mb_left)
    {
      with oPlayer
      {
        // DO STUFF
      }
      break; //required if the two checks are exclusive
    }
  }
}
You can definitely do the same thing avoiding the loop by changing the conditions a bit, but the above is a bit more flexible to work with.

@Rui Rosário Ninja'd :(
 
Top