DanPaul
DanPaul

Reputation: 21

How to detect if a shape hits another in html5 canvas?

I'm trying to build a motorbike game in html5 canvas with javascript. Right now I have a wheel and a simple gravity which increases the position from the top of the canvas until the wheel hits the bottom of the canvas. When I start the game, the wheel just drops to the bottom of the canvas.

I want to create a curved ground for the wheel to ride on. The problem is that I don't know how to calculate if the wheel hits this ground.

Here is a illustration. I want the wheel to drop until it hits the curved ground, and if I'm moving the wheel, it needs to follow the shape's edge.

image http://i.minus.com/iFvy1dbnouvy6.png

I don't want to use any libraries or engines, only javascript and html5. Do you have any ideas or solutions?

Upvotes: 2

Views: 794

Answers (3)

user372551
user372551

Reputation:

Here is the solution which you're looking for Collision Detection (elastic)..
.--------------------------------------------------------------------------------------------.
Here's a simple & Good tutorial for learning physics especially for Game Developers

Upvotes: 0

Tom Prats
Tom Prats

Reputation: 7931

Similar to the other answer, you can simply have an if statement that says

if tire.y < line(tire.x) then tire.y = line(tire.x) - 1

the line function can just be an array or some formula that will contain the y value of the line when given any x-value.

Upvotes: 1

user278064
user278064

Reputation: 10180

In order to detect when the wheel hits the ground, you should have the coordinates of the ground boundary (e.g.: a polyline) and the wheel's ray and center position.

You detect collision by checking that your wheel y coordinate (cener + ray) is below the y coordinate of your polyline at certain x(s). You should segment your polyline in a resonable way, by carefully selecting your endpoints.

Probably there are other ways to accomplish this task, but this is the first which I came out.

Upvotes: 0

Related Questions