topdown shooting help
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
topdown shooting help
theres this really weird bug that happens where when you shoot, the bullets are basically still tracking the mouse and its not really working correctly. if somebody could please take a look at this and help, it would be greatly appreciated!
- Attachments
-
- dung.love
- (2.47 KiB) Downloaded 65 times
Re: topdown shooting help
Code: Select all
function player:update(dt)
....
for _,v in ipairs(self.bullets) do
local e = 200
local mx, my = love.mouse.getPosition()
local w = math.atan2(my-self.body:getY(), mx-self.body:getX())
v.body:setX(v.body:getX()+math.cos(w)*e*dt)
v.body:setY(v.body:getY()+math.sin(w)*e*dt)
end
That position is the mouse-position plus some rotation but that makes no sense, think about it:
The mouse position only matters when aiming the gun. After the bullet is fired it should just continue on its path, the mouse position has become irrelevant.
Just for completeness, movement of object is usually something like this:
Code: Select all
newX=oldX+speedX*dt
newY=oldY+speedY*dt
Instead, use setLinearVelocity() to set the bullet's X&Y speed when it is created.
Re: topdown shooting help
Just fixed this two functions in src/player.lua:
Code: Select all
function player:shoot(dt)
local px, py = self.body:getPosition()
local w = math.atan2(love.mouse.getY()-px, love.mouse.getX()-py)
local bullet = {}
bullet.body = love.physics.newBody(world, self.body:getX()+math.cos(w), self.body:getY()+math.sin(w))
bullet.shape = love.physics.newCircleShape(10)
bullet.fixture = love.physics.newFixture(bullet.body, bullet.shape)
-- local e = 200
local speed = 200
local mx, my = love.mouse.getPosition()
local angle = math.atan2(my-self.body:getY(), mx-self.body:getX())
bullet.vx = speed * math.cos (angle)
bullet.vy = speed * math.sin (angle)
table.insert(self.bullets, bullet)
end
function player:mousepressed(button)
if button == 1 and pistol.unlocked then
self:shoot(love.timer.getDelta())
end
end
function player:update(dt)
local rot = math.atan2(love.mouse.getY()-self.body:getY(), love.mouse.getX()-self.body:getX())
for _, bullet in ipairs(self.bullets) do
-- local e = 200
-- local mx, my = love.mouse.getPosition()
-- local w = math.atan2(my-self.body:getY(), mx-self.body:getX())
local dx = dt*bullet.vx
local dy = dt*bullet.vy
bullet.body:setX(bullet.body:getX()+dx)
bullet.body:setY(bullet.body:getY()+dy)
end
-- rotate player towards the mouse
self.body:setAngle(rot)
local vx = 0
local vy = 0
if love.keyboard.isDown("a") then
vx = self.speed * -1
end
if love.keyboard.isDown("d") then
vx = self.speed * 1
end
if love.keyboard.isDown("w") then
vy = self.speed * -1
end
if love.keyboard.isDown("s") then
vy = self.speed * 1
end
self.body:setLinearVelocity(vx, vy)
end
Who is online
Users browsing this forum: No registered users and 8 guests