Loading...
Logo
Processing Forum
I'm creating a game where you, a little point, have to run away from other little points, and if they touch you, you die. Pretty standard game format, but I'm having a lot of trouble getting the little points to follow the player.

I've tried:
Copy code
  1.  if (x > targetX) x -= speed;
  2.  if (x < targetX) x += speed; 
  3.  if (y > targetY) y -= speed;
  4.  if (y < targetY) y += speed;
But of course that only allows the little points to move in 45 degree angles.

I then tried something like:
Copy code
  1.  x += (targetX - x) * speed;
  2.  y += (targetY - y) * speed;
But then the speed of the particles is dependent on the distance between the particle and the player. When they're really far away, they're super fast, when they're really close, they're really slow. I need a constant speed.

Finally I tried trigonometry:
Copy code
  1. xCalc = xTarget - x; //'bottom' of the triangle, adjacent to angle
  2. yCalc = yTarget - y; //'side' of the triangle, opposite angle
  3. angle = atan(yCalc/xCalc);
This works well along the x-axis, but not at all well along the y-axis. It also doesn't work from 3'o'clock to 6'o'clock, the bottom right quadrant - if the player is in this position compared to the particle, the particle ignores the player. I'm sure this last way is the right way to go but I can't get my head around the maths. Help?

Replies(5)

Without deep analysis (so I can be wrong), you might want atan2(), more often used to compute an angle from two coordinates.
Hi Macko,

I've made a quick sketch where a little dude follows the mouse cursor on a constant speed. I think it would be easy to adapt it to your game and also add other dudes. It would also be very easy to set the speed according to the distance from the player. You could always use rotate, but I think it is always good to exercise some trigonometry :)

float dudeSpeed = 5.;
Boolean started = false;
PVector littleDude;


void setup() {
  smooth();
  size(800,600);
  littleDude = new PVector(random(width), random(height), 0.);
  ellipseMode(CENTER);
  noStroke();
  fill(255, 0,0);
}

void draw() {
  background(0);
  ellipse(littleDude.x, littleDude.y, 5, 5);
  float angle = atan2(mouseY-littleDude.y, mouseX-littleDude.x);
  float newX = cos(angle) * dudeSpeed + littleDude.x;
  float newY = sin(angle) * dudeSpeed + littleDude.y;
  littleDude.set(newX, newY, 0.);
}

Cheers,
Miguel
How would you make an object follow another moving object by using rotate?
Of course, there is always the PVector Tutorial. (The example towards the bottom is very useful.)
Thanks Miguel, that works really well. He goes little crazy once he reaches the target, but that shouldn't be an issue I hope, because the player dies if anything touches him. Worse comes to worst I can alter the algorithm to my first, 45-degree-only one once they get within a few pixels range.