Set velocity based on rotation

I’m messing around with a simple prototype idea but I’m having trouble with what I thought would be a fairly trivial thing.

I am trying to make it so that when the player touches the screen my plane (currently a rectangle) will rotate to point to the touch position (which is working fine) but also move towards it (this is where the trouble starts).

If you run the simple code you will see the strange things such as a sort of wiggle when re-orientating and also not quite perfect movement angle.

Any ideas as to what I’ve done wrong?

Here is the code for my “mail.lua”:

  
physics = require "physics"  
physics.start()  
physics.setGravity( 0, 0 )  
  
local plane = require("plane")  
  
local player = plane.new()  
  
local onUpdate = function(event)  
 player:update()  
end  
  
Runtime:addEventListener("enterFrame", onUpdate)  
  

And here is the code for my “plane.lua”:

[code]

module(…, package.seeall)

require “sprite”

function new()
local self = display.newRect( 50, 50, 50, 10)
self:setFillColor( 0, 255, 0 )

physics.addBody( self, { density = 1.0 })

local runtimeTouch = function(event)
self.targetPosition = {x=event.x, y=event.y}
end

function self:update()

if(self.targetPosition) then
local targetRotation = math.atan2((self.targetPosition.y - self.y), (self.targetPosition.x - self.x))

local difference = targetRotation - self.rotation

self.rotation = math.deg(self.rotation + difference)
end

self:setLinearVelocity( math.cos(self.rotation) * 50, math.sin(self.rotation) * 50)
end

Runtime:addEventListener(“touch”, runtimeTouch)

return self
end

[/code] [import]uid: 5833 topic_id: 3634 reply_id: 303634[/import]

don’t know what you’ve done wrong but i adapted this one from some flash code
http://developer.anscamobile.com/forum/2010/11/11/code-turn-towards-follow-mouse [import]uid: 6645 topic_id: 3634 reply_id: 11053[/import]

Ah ha, that works brilliantly thank you very much :slight_smile: [import]uid: 5833 topic_id: 3634 reply_id: 11057[/import]