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?
Move x pixels towards target
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
- ken.athomos
- Citizen
- Posts: 77
- Joined: Fri Aug 05, 2016 10:13 am
- Location: Philippines
Re: Move x pixels towards target
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?
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?
Re: Move x pixels towards target
You need to normalize the vector that points from bullet to target.
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.
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)
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.
Re: Move x pixels towards target
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.
- zorg
- Party member
- Posts: 3449
- Joined: Thu Dec 13, 2012 2:55 pm
- Location: Absurdistan, Hungary
- Contact:
Re: Move x pixels towards target
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 True 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.
Who is online
Users browsing this forum: Bing [Bot], Google [Bot], Majestic-12 [Bot] and 1 guest