I was trying to write a code where i wanted to shoot a ball to a specific direction. Its more like the game bubble bust so the gun or shooter can be rotated and ball will be shot depending on the current direction of the gun. i managed to write a code to rotate the gun and also shoot the ball from the current position but having difficulties in moving the ball on the exact path aligned with the gun direction. Any help? Just a hint would be a lot. Thanks.
When your gun “fires” a bullet, copy the gun’s position and direction at that moment when you spawn the bullet. Then, each frame, update the bullet’s position with:
bullet.position = bullet.position + bullet.direction * bullet.speed
Where bullet.speed is whatever you like.
Here’s some pseudo code (not fully implemented) that might help.
-- We get these from somewhere
gunDirection = vec2(...)
gunPosition = vec2(...)
bullets = {} -- our table of bullets
function spawnBullet()
bullet = {}
bullet.position = gunPosition
bullet.direction = gunDirection
bullet.speed = 10
-- add bullet to table
table.insert( bullets, bullet )
end
function removeOffscreenBullets()
-- Go through the bullets table and remove
-- any bullets that are out of bounds
end
function updateBullets()
for i,bullet in ipairs(bullets) do
bullet.position = bullet.position + bullet.direction * bullet.speed
end
end
function draw()
-- We do some drawing...
updateBullets()
-- Check for some condition (e.g. user taps screen) and spawn a bullet
spawnBullet()
removeOffscreenBullets()
-- Draw each bullet
fill(255,0,0)
for i,bullet in ipairs(bullets) do
ellipse( bullet.position.x, bullet.position.y, 40, 40 )
end
end