Hi,
I have an issue and hope you can help.
If we think “asteroids” of which there is a good example in the code share forum.
Now I have an object which will orientate itself to the users touch, no probs.
I have bullets which will spawn and move from objects x.y. position, no probs.
The issue I have is I need the bullets to fire in the direction at which the touch event ended.
I have used a code snippet from code exchange for the rotation.
I figure I have to pass the ended co-ords from the rotation function to the bullet function ?
Or could I use the ended touch event co- ord?
here is some simplified code, plug and play, no need to worry about bullet spawn etc, just need the bullet to orientate its self to object “ended” position.
Thanks for the advice
local physics = require('physics')
physics.start()
physics.setGravity(0, 0)
--physics.setDrawMode( "hybrid")
local ship = display.newRect( 50, 50, 50, 50 )
ship.x = 200
ship.y = 200
local transRect = display.newRect(0,0, 1024, 768)
transRect.isVisible = false
transRect.isHitTestable = true
ship:setReferencePoint(display.CenterReferencePoint)
local math\_deg = math.deg --localize 'math.deg' for better performance
local math\_atan2 = math.atan2 --localize 'math.atan2' for better performance
--This function should reside outside and above the touch function
local function angleBetween( srcX, srcY, dstX, dstY )
local angle = ( math\_deg( math\_atan2( dstY-srcY, dstX-srcX ) )+90 ) --; return angle
if ( angle \< 0 ) then angle = angle + 360 end ; return angle % 360
end
local function touchRect ( event )
local ang = angleBetween( ship.x, ship.y, event.x, event.y )
ship.rotation = ang
if event.phase == "began" or event.phase == "moved" then
print ("BEGAN/MOVED " )
elseif event.phase == "ended" then
bullet()
end
end
function bullet()
local bullet = display.newRect( 10, 10, 10, 80 )
bullet:setFillColor (255,0,0)
bullet.x = ship.x -10
bullet.y = ship.y -10
bullet.name = 'bullet'
physics.addBody(bullet)
end
transRect:addEventListener( "touch", touchRect )
[import]uid: 127675 topic_id: 32966 reply_id: 332966[/import]