I would like to shoot a projectile towards a point in space (in a 2D game). I have something almost working but I can't get my head round how to fix it.
I would like to solve the following:
1) How to shoot in a certain direction not just where the mouse is (I could only get it working right with this mouse pointer method but in reality I just want to shoot something in a direction (and maybe not use mouse).
2) The projectiles shoot out sort of 90 degrees to where the mouse pointer is but I want them to shoot at where mouse pointer is. I seem to get automatically very confused when thinking about angles.
3) At certain positions (90 degrees?) the projectiles sort of flip to the other side when I really just want it to track smoothly all the way round.
Here is the code. Can anyone help? Maybe there is just a better way to do it?
function App:Start()
--Create a window
self.window = Window:Create()
self.context = Context:Create(self.window)
self.world = World:Create()
local camera = Camera:Create()
camera:SetRotation(35,0,0)
camera:Move(0,0,-6)
local light = DirectionalLight:Create()
light:SetRotation(35,35,0)
--Create a model
self.model = Model:Box()
return true
end
function App:Loop()
if self.window:Closed() or self.window:KeyHit(Key.Escape) then return false end
--Get the vector between the mouse position and the center of the screen
local v = self.window:GetMousePosition()
local dx = v.x - self.context:GetWidth()/2.0
local dy = self.context:GetHeight()/2.0 - v.y
v = Vec3(dx,dy,0):Normalize()
--Align the model to the vector
self.model:AlignToVector(v,2)
-- Create projectile
bullet = Model:Sphere()
bullet:SetPosition(5,0,0)
bullet:SetMass(1.0)
-- Align to mouse pointer vector
bullet:AlignToVector(v, 2)
-- Add velocity
bullet:SetVelocity(Vec3(0,10,0), false )
Time:Update()
self.world:Update()
self.world:Render()
self.context:Sync()
return true
end
Thanks,
Michael