If pressed the up button — game object should move by 128 pixels on the y-coordinate. If pressed the down button — game object should move by -128 pixels on the y-coordinate. So my game object has 4 movements: from center to top, from top to center, from center to bottom and from bottom to center.
function init(self)
msg.post(".", "acquire_input_focus")
self.movement = false
self.targetPos = vmath.vector3()
self.maxYCoord = 696
self.minYCoord = 440
end
function update(self, dt)
if self.movement then
local pos = go.get_position()
pos = pos + self.targetPos
go.set_position(pos)
end
self.targetPos.y = 0
self.movement = false
end
function on_input(self, action_id, action)
if action_id == hash("up") and action.pressed and go.get_position().y < self.maxYCoord then
self.targetPos.y = 128
self.movement = true
elseif action_id == hash("down") and action.pressed and go.get_position().y > self.minYCoord then
self.targetPos.y = -128
self.movement = true
end
end
One common way to get smooth motion, is to use the delta time variable (dt).
With it you know how much time has lapsed between the last frame and the current.
Here’s a simple example of how to do it.
function init(self)
msg.post(".","acquire_input_focus")
self.speed = 50 -- pixels per second
self.direction = vmath.vector3(0,0,0)
end
function update(self, dt)
local position = go.get_position() + (dt * self.speed) * self.direction
go.set_position(position)
self.direction = vmath.vector3(0,0,0)
end
function on_input(self, action_id, action)
if action_id == hash("left") then
self.direction.x = self.direction.x - 1
end
if action_id == hash("right") then
self.direction.x = self.direction.x + 1
end
if action_id == hash("up") then
self.direction.y = self.direction.y + 1
end
if action_id == hash("down") then
self.direction.y = self.direction.y - 1
end
end
Hi Im trying to do a smooth movement, I have somehting like you post, but I want to add aceleration and I dont know how to implement It.
Anyone can help me pelase?
I am adding in self.direction.x +1 for example without reset betwen frames, but I am normalizing the vector later, then I lost the aceleration, how can I implement aceleration and have the movement normalized? (character going the same speed in diagonal and straight