Let’s move to collision checking part. I did not use the built-in physic engine so I had to do it in my own way:

– Register a list of targets by using an array to store targets. There are two types of targets

- One already has its implementation of collision checking itself
- One does not have, we have to implement it manually by calculating distance between the arrow and the target

– Repeatedly do collision checking for each target in the array of targets while updating the arrow’s position

– If collision occurs on a target, save it into an array of hit targets

– Returns the array that stores the hit targets

– Invoke the callback function (called onCollision in my program).

That’s it!!!

Code for collision checking:

self.isCollided = function()

-- storing collision data

local ev = {}

```
```-- count the hit targets

local cnt = 0

if self.targets ~= nil then

for i = 1, #self.targets do

-- if collision check is implemented

if self.targets[i].isCollided ~= nil then

local isHit = self.targets[i].isCollided(self.arrowui.x, self.arrowui.y)

if isHit then

cnt = cnt + 1

ev[cnt] = {}

ev[cnt].target = self.targets[i]

ev[cnt].x, ev[cnt].y = self.arrowui.x, self.arrowui.y

ev[cnt].angle = self.arrowui.rotation

end

-- if the collision checking is not implemented on the target, then use accuracy

else

-- compute the distance between the arrow and a target

local d = (self.arrowui.x - self.targets[i].x) ^ 2 + (self.arrowui.y - self.targets[i].y) ^ 2

-- compare the distance

if (d < accuracy ^ 2) then

cnt = cnt + 1

ev[cnt] = {}

ev[cnt].target = self.targets[i]

ev[cnt].x, ev[cnt].y = self.arrowui.x, self.arrowui.y

ev[cnt].angle = self.arrowui.rotation

end

end

end

end

`return ev`

end

The purpose of this is to simulate the event whenever the arrow hits a registered target. We can implement what happens in the event manually as we wish.

Here’s the code:

-- implement the collision event

myBow.onCollision = function(ev)

local hits = #ev

if hits > 0 then

-- reload the bow

myBow.reload()

```
```-- draw the arrow at the target

local arrow = display.newImage("Images/arrow.png", 0, 0)

-- retrieving event's data

arrow.x, arrow.y = ev[1].x, ev[1].y

arrow.rotation = ev[1].angle

`-- set the scale`

arrow.xScale = bowHeight / arrow.height / 2

arrow.yScale = bowHeight / arrow.height / 2

end

end

Please see the whole source code. Enjoy!

### Like this:

Like Loading...

## Published by Quang Le

I am a 10+ year exp programmer, a data analyst. My favorites are math, computer science, and football.
View all posts by Quang Le

## 1 thought on “Corona SDK – An implementation of bow shooting without physic engine 2 – Collision check”