0
\$\begingroup\$

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

    physics.addBody( bullet )

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

Runtime:addEventListener( "touch", onScreenTouch )
\$\endgroup\$
1
\$\begingroup\$

Basically you will want to do something like this:

deltaX = event.x - playerX
deltaY = event.y - playerY
normDeltaX = deltaX / math.sqrt(math.pow(deltaX,2) + math.pow(deltaY,2))
normDeltaY = deltaY / math.sqrt(math.pow(deltaX,2) + math.pow(deltaY,2))

... 
bullet:setLinearVelocity( normDeltaX  * speed, normDeltaY  * speed )
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.