This site requires JavaScript, please enable it in your browser!
Greenfoot back
qweasdzxc
qweasdzxc wrote ...

2014/1/30

Actor moves to location I haven't set...

qweasdzxc qweasdzxc

2014/1/30

#
I have used this code to keep my actor within the edge of a rectangle with the middle cut out. However, when I move into 3 of the sides, instead of just preventing it to move it spawns it into another corner. The first statement is working fine for the bottom left corner, it is all the others that do not do as they should. if(getX() <= 47 || getY() >= 466) { setLocation(48, 465); } if(getX() <= 47 || getY() <= 47) { setLocation(48, 48); } if(getX() >= 977 || getY() <= 47) { setLocation(976, 48); } if(getX() >= 977 || getY() >= 466) { setLocation(976, 465); }
Gevater_Tod4711 Gevater_Tod4711

2014/1/30

#
The problem is that you check the x and y coordinates at the same time and so if the actors position is (47|50) the first if clause will be true because of the logical OR and so the position of your actor is set to (48|465). Instead you should try to check only one component of the actors position at one time like this:
if (getX() <= 47) {
    setLocation(48, getY());
}
if (getY() <= 47) {
    setLocation(getX(), 48);
}
//...
qweasdzxc qweasdzxc

2014/1/30

#
Ok thanks, I will give that a try.
qweasdzxc qweasdzxc

2014/1/30

#
It fixed the earlier problem, but now if I try to move it left in 1 corner then because of another if statement it means that it is also stuck to that corner and I can move it outside the desired area.
qweasdzxc qweasdzxc

2014/1/30

#
I basically want the if statement to read if this and this are true then setLocation for example. If not then it can carry on moving as it wants.
Gevater_Tod4711 Gevater_Tod4711

2014/1/30

#
If you need to connect the boolean values using a logical AND and no OR you need to change the operator || to &&.
qweasdzxc qweasdzxc

2014/1/30

#
Alright I will try something along those lines thanks again.
danpost danpost

2014/1/31

#
Neither AND ( && ) nor OR ( || ) will produce the result you want. You already saw the result of using OR; and AND will adjust the location of the actor only when both of two adjacent edges are breached. That is, the actor will be able to proceed past any edge horizontally or vertically, but not pass the corners diagonally.
You need to login to post a reply.