Move x pixels towards target

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
pauls313
Citizen
Posts: 50
Joined: Tue Aug 02, 2016 3:07 am

Move x pixels towards target

Post by pauls313 »

This is probably a really stupid problem, but anyway:
I have a bullet, and I want it to move, let's say, 2 pixels towards a target every frame. I already know how to move it towards something, like this:
x = x + ((targetx - x) / 5)
But it obviously slows down over time. It's smooth

How can I move it an exact amount of pixels every frame?
User avatar
ken.athomos
Citizen
Posts: 77
Joined: Fri Aug 05, 2016 10:13 am
Location: Philippines

Re: Move x pixels towards target

Post by ken.athomos »

Is it okay for you to attach a .love file of the thing you're working on?

Anyways, I'm assuming that the bullet is moving downwards to the target based on your equation. Have you tried using dt? If so, what happens?
User avatar
pgimeno
Party member
Posts: 3593
Joined: Sun Oct 18, 2015 2:58 pm

Re: Move x pixels towards target

Post by pgimeno »

You need to normalize the vector that points from bullet to target.

Code: Select all

function normalize2d(x, y)
  if x == 0 and y == 0 then return 0, 0 end
  local length = math.sqrt(x*x + y*y)
  return x/length, y/length
end

...
  local dirx, diry = normalize2d(targetx - bulletx, targety - bullety)
  bulletx = bulletx + dirx * (dt * bulletspeed)
  bullety = bullety + diry * (dt * bulletspeed)
Normalizing a vector means to obtain a vector of length 1 that points in the same direction as the given one. That's exactly what you need, because that way, you can multiply it by the bullet speed, to obtain a bullet velocity vector that points in that direction.

Note in the above code, bulletspeed is in pixels/s, and dt is the delta time coming as a parameter in the love.update event.
pauls313
Citizen
Posts: 50
Joined: Tue Aug 02, 2016 3:07 am

Re: Move x pixels towards target

Post by pauls313 »

I tried your code but I get the error ""=" expected near "==" in line 22". The line 22 would be the second line in your code.
User avatar
zorg
Party member
Posts: 3449
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Move x pixels towards target

Post by zorg »

pgimeno's snippets are syntactically correct, so again, paste the relevant code part and the full error message at least. A screenshot would work too, probably.
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests