Circle-Rectangle Collision Detection
Posted: Sat May 04, 2013 2:24 am
So, let me start out by saying that I already have a code that sort of works... or at least it looks like it... from far away.
This is the code I have so far (FYI: I have the bullet very slow and large for testing purposes)-
bullet.lua:
enemy.lua:
main.lua:
I guess what I'm really wondering is if there is a better way to do this without using HardAgon?
You can also use the arrow keys to move the player around just to speed up the process if you like.
This is the code I have so far (FYI: I have the bullet very slow and large for testing purposes)-
bullet.lua:
Code: Select all
require "enemy"
bullet = {}
bullet.speed = 500
function bullet:draw()
for i, v in ipairs(bullet) do
if v.id == true then
love.graphics.setColor( 255, 255, 255 )
love.graphics.circle( "fill", v.x, v.y, v.r )
end
end
end
function bullet:update(dt)
for i, v in ipairs(bullet) do
if v.id == true then
v.x = v.x + v.dx * dt
v.y = v.y + v.dy * dt
else
v.x = nil
v.y = nil
v.r = nil
end
end
end
function bullet:shoot( x, y )
mouseX = x
mouseY = y
startX = player.x
startY = player.y
dir = math.atan2(( mouseY - player.y ), ( mouseX - player.x ))
bulletDx = bullet.speed * math.cos(dir)
bulletDy = bullet.speed * math.sin(dir)
table.insert( bullet, { x = startX, y = startY, dx = bulletDx, dy = bulletDy, r = 200, id = true } )
end
function bullet:collide() --note that bullet.x and bullet.y are located in the middle of the circle.
for i, bullet in ipairs(bullet) do
for ii, enemy in ipairs(enemy) do
if bullet.id == true then
if bullet.x + bullet.r > enemyA and
bullet.x - bullet.r < enemyB and
bullet.y + bullet.r > enemyA and
bullet.y - bullet.r < enemyC then
print("hit!")
bullet.id = false
enemy.id = false
end
end
end
end
end
Code: Select all
enemy = {}
function enemy:draw()
for i, v in ipairs(enemy) do
if v.id == true then
love.graphics.setColor( 255, 0, 0 )
love.graphics.rectangle( "fill", v.x, v.y, v.w, v.h )
end
end
end
function enemy:update(dt)
for i, v in ipairs(enemy) do
if v.id == true then
enemyA = v.x
enemyB = v.x + v.w
enemyC = v.y + v.h
end
end
end
function enemy:load( x, y, w, h )
table.insert( enemy, { x = x, y = y, w = w, h = h, id = true } )
end
Code: Select all
function love.load() --Run only at start of game
enemy:load( 400, 400, 32, 32 )
end
function love.draw() --Run every time game can
player:draw()
bullet:draw()
enemy:draw()
end
function love.update(dt) --Run every time the game can
bullet:update(dt)
bullet:collide()
player:update(dt)
enemy:update(dt)
end
You can also use the arrow keys to move the player around just to speed up the process if you like.