简体   繁体   中英

Javascript collision detection on canvas

I am struggling with writing collision detection for the sword and the enemy. Attempting to implement coordinates for the sword using variable swdX and swdY have caused the sword to morph rather than follow the character and maintain shape.

The collision code I am using is

//subtract hp enemy on sword swing
if (swdX == enmX){
    enmhplevel--;
}

However, my output for swdX never shows swdX as changing.

A link can be found here.

http://jsfiddle.net/Qt7zd/3/

Pointy - All of my code is on the JSfiddle. I tried updating the loop with

swdX == posX +80;
swdY == posY -40; 

however, this does not update the coordinates. Do you have any pointers?

Adding swdX = posX +80; swdY = posY -40; swdX = posX +80; swdY = posY -40; into the loop does update the coordinates fine. In you question however, you have == , which is not assignment, it is an equals operator.

Then your collision detection in this example needs be expanded to accommodate the radius of the enemy (so the sword hits if the point is anywhere inside the enemy, not just perfectly on it's center), and the angle of the sword (so it doesnt hit when the sword is rotating somewhere not on the enemy).

if ((swdX >= enmX - 30 || swdX > enmX + 30) && (Z % 360 >= 10 && Z % 360 < 60)) {
    enmhplevel--;
}

You'd definitely need to get rid of the hardcoded constants, consider the y direction, consider when the point of the sword is through the enemy, etc, for a game, but the example is working here: http://jsfiddle.net/j84zU/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM