In the code below I need to fire something towards another object using Atan2, cos and sin
It works, but I'm converting to degrees and then back to radians. (I'm guessing this has some overhead).
Snippet:
| 	local angle = math.atan2(yDiff,xDiff)
	angle = math.deg(angle) + 180
 
	local nextX = ball:getX() + (math.cos(math.rad(angle)) * move)
	local nextY = ball:getY() + (math.sin(math.rad(angle)) * move) | 
Is there a better way to 'reverse' the angle?
Thank you!
| -- Add hero
 
local hero = Bitmap.new(Texture.new("gfx/happy-block.png"))
hero:setAnchorPoint(.5,.5)
stage:addChild(hero)
hero:setPosition(100,100)
 
-- Add ball
 
local ball = Bitmap.new(Texture.new("gfx/ball.png"))
ball:setAnchorPoint(.5,.5)
stage:addChild(ball)
ball:setPosition(400,200)
 
 
-- pixels moved each frame
local move = 1;
 
local moving = false -- keep track of if ball already moving
 
-- This function moves the ball each frame
 
function moveBall()
 
	local xDiff = ball:getX() - hero:getX()
	local yDiff = ball:getY() - hero:getY()
 
	local angle = math.atan2(yDiff,xDiff)
	angle = math.deg(angle) + 180
 
	local nextX = ball:getX() + (math.cos(math.rad(angle)) * move)
	local nextY = ball:getY() + (math.sin(math.rad(angle)) * move)
 
	--print(nextX, nextY)
 
	ball:setPosition(nextX,nextY)
 
end
 
function touchedEnd(event)
 
	if(not moving) then
 
		moving = true
		ball:setPosition(event.touch.x, event.touch.y) -- move ball to touch x,y
		stage:addEventListener(Event.ENTER_FRAME, moveBall) -- add event listener to move ball each frame
 
 
	end
 
end
 
stage:addEventListener(Event.TOUCHES_END, touchedEnd) | 
Comments
Likes: Tom2012
#MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
So, you can store any math functions you're going to use like:
Likes: techdojo
#MakeABetterGame! "Never give up, Never NEVER give up!" - Winston Churchill
Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
Cool Vizify Profile at https://www.vizify.com/oz-apps