Simple move to target script

I couldn’t find an example for this anywhere so I had a go myself starting with the player script from the War Battles tutorial. Basically, the game object should move towards the touch or click position on input and stop when it reaches the target.

local input_click = hash('click')
local input_touch = hash('touch')

local function target_reached(target, current)
    return math.floor(target.x) == math.floor(current.x) and math.floor(target.y) == math.floor(current.y)
end

function init(self)
    msg.post('.', 'acquire_input_focus')
    self.target_position = vmath.vector3(0, 0, 0)
    self.direction = vmath.vector3(0, 0, 0)
    self.moving = false
    self.speed = 50
end

function update(self, dt)
    if self.moving then
        local position = go.get_position()

        position = position + self.direction * self.speed * dt
        go.set_position(position)

        if target_reached(self.target_position, position) then
            self.moving = false
            self.target_position = vmath.vector3(0, 0, 0)
        end
    end
end

function on_input(self, action_id, action)
    if action_id == input_click or action_id == input_touch then
        self.target_position = vmath.vector3(action.x, action.y, 0)
    end

    if vmath.length(self.target_position) > 0 then
        self.moving = true 
        self.direction = vmath.normalize(self.target_position - go.get_position()) 
    end
end
1 Like

Thanks. An alt take can be found among the examples in the learn section: https://www.defold.com/examples/basics/follow/

1 Like

Clearly I didn’t look very hard! Thanks

1 Like

Edit: Reset self.target_position when target is reached to prevent any other input action triggering movement.

Hey, if someone here want to move a character with this method : you probably need to use a constant move speed.
I made a script by myself, I’d be happy if semone else shared it earlier :wink:

function init(self)
    self.moveSpeed = 100
end

function on_input(self, action_id, action)
if action_id == hash("click") and action.pressed then 
    if not self.moving then 
        msg.post("#label", "disable") 
        self.moving = true 
        targetPos = vmath.vector3(action.x, action.y, 0) 
        pos = go.get_position()
        local cx = pos.x - action.x
        local cy = pos.y - action.y
        local norm = math.sqrt((cx*cx)+(cy*cy))
        local travelTime = norm / self.moveSpeed
        go.animate(".", "position", go.PLAYBACK_ONCE_FORWARD, targetPos, go.EASING_LINEAR, travelTime, 0, landed) 
    end 
  end
end

It is basic maths but I think it will help someone one day

3 Likes