# How to shoot on direction of touch

I'm new to the Corona SDK(and I also suck in trigonometry) and I'm trying to achieve this:

Shoot a bullet from the player, towards the direction of the point the user touched, but always with ethe same speed, regardless of how far the touch was from the player.

I have tried several solutions. After some research I saw that I should calculate the angle from the two deltas in degrees, and then use the cos and sin of the angle as the x and y values respectively. But when I try to do so, I get pretty random results.

The closer I was able to get from what I want to achieve was to use the delta variables as the X and Y (multiplied by the speed factor). It worked, but then the speed varied based on how far from the player I touched and I want the speed to be fixed.

Here's my latest code(using sin and cos)

local math, physics = require("math"), require('physics')

physics.start()
physics.setGravity( 0, 0 )

display.setStatusBar( display.HiddenStatusBar )

local screenW, screenH = display.contentWidth, display.contentHeight
local playerX, playerY = (screenW / 2), (screenH / 2)

local player = display.newRect( 0, 0, 30, 30 )
player.x = playerX
player.y = playerY

-- local sinT = display.newText("", 100, 10)
-- local cosT = display.newText("", 100, 30)
local angleT = display.newText("", 100, 70)

local function onScreenTouch( event )
if (event.phase == "began") then
speed = 3
deltaX = event.x - playerX
deltaY = event.y - playerY

angle = math.atan2( deltaY, deltaX ) * 180 / math.pi

-- sin, cos = math.sin( angle ), math.cos( angle )

-- sinT.text = sin
-- cosT.text = cos
angleT.text = angle

bullet = display.newRect( 0, 0, 6, 6 )
bullet.x = playerX
bullet.y = playerY

bullet:setLinearVelocity( math.cos( angle ) * speed, math.sin( angle ) * speed )
end
end


• Possible duplicate: gamedev.stackexchange.com/questions/13326/…. It's actually much less difficult than you're making it. This can easily be done with vectors. You already have the first bits, take your deltaX and deltaY and normalize them. Then scale them by the speed you want.
– House
Sep 25 '13 at 5:21
• I don't know much about your engine but just for getting some inspiration, I think It's not a bad idea to take a short look at my old Q&A : How to correct shooting in touch-screen shooting games? Sep 25 '13 at 5:22

deltaX = event.x - playerX