Let the image object move in different directions

Hi everyone! I need some help with understanding, what can I use to make an image object move in the specified direction(vectors maybe…I am not that sure).
I have an object that is represented by png image and I want it to move for a speified distance and in a direction, that would be defined by click. If I click on the left near the image it should move right, if I click on the top near the image it should go down and vice versa. For diagonals it should also work the same way e.g.left upper corner click sends image to right down corner.
I’ve tried to find a tutorial or an example on https://processing.org/ , but didn’t really find something like this. If you’ve seen such a tutorial I would be grateful if you share a link. Or maybe you can write a hint, how to do it. Thanks!!!

Let’s say your object is at x,y.

You move it by


x+=xadd; 
y+=yadd;

xadd and yadd can be positive or negative.

Now, use the function mousePressed() and compare the mouse pos mouseX, mouseY
with x,y.
When

  • mouseX < x say xadd = -1;
  • mouseX > x say xadd = 1;
  • mouseY < y say yadd = -1;
  • mouseY > y say yadd = 1;

So you can get a vertical, diagonal and horizontal movement.

For movement in any direction see atan2 - Understanding the Atan2, Please help - #6 by CodeMasterX

1 Like

Oh, the thing with xadd = -1 didn’t come to my mind. Thanks a lot! I’ m going to try it now!

1 Like

@Chrisir one more question. Is it possible to save mouseX and mouseY value when mousePressed(), so I can use them a little later?

sure just say

in mousePressed()

mouseXStored = mouseX; 
mouseYStored = mouseY;

(and set a timer?)

and of course before setup()

int mouseXStored, mouseYStored;

Thank you so much! Your answers hepled me a lot!

When you view the position where the mouse has been clicked as a TARGET (and not only as the general direction, like a form of cursor keys), consider the following:

you can calc the difference between target and current position and add that to the current position, thus player moves towards mouse position. You can make an easing, so it moves slowly towards it

cf. Slow Movement of player to mouse position on mouse click - #2 by Chrisir

I’ve already implemented) I needed the image to go in other direction from where mouse was clicked. Thanks!

1 Like