JS: Game Obstacles
Let's turn some of the game components into obstacles to make the game more interesting.
Adding collision function
As we saw at the end of the previous lesson, our character object passed through the obstacles like we pass our fingers through the liquid. So, we need to turn these component obstacles into solid. Hence, we will define a method inside the character
object that will prevent the character from passing through those collisions.
Press + to interact
collision(obj) {if((this.y > obj.y+3 && this.y < obj.y + obj.h - 3) || (this.y + this.size > obj.y + 3 && this.y + this.size < obj.y + obj.h - 3)){// right collisionif((Math.floor(this.x) <= obj.x + obj.w) && (Math.floor(this.x) >= obj.x + obj.w - 5)){this.rflag = 0;this.deltaX = 0;}// left collisonif((Math.floor(this.x + this.size) >= obj.x) && (Math.floor(this.x + this.size) <= obj.x + 5)){this.lflag = 0;this.deltaX = 0;}}if((this.x > obj.x + 3 && this.x < obj.x + obj.w - 3) || (this.x + this.size > obj.x + 3 && this.x + this.size < obj.x + obj.w - 3)){// downward collisionif((Math.floor(this.y) <= obj.y + obj.h) && (Math.floor(this.y) >= obj.y + obj.h - 5)){this.deltaY = -this.deltaY;}//upward collisionif((Math.floor(this.y + this.size) >= obj.y) && (Math.floor(this.y + this.size) <= obj.y + 5)){this.y = obj.y - this.size;this.deltaY = 0;this.groundCollision = true;}}}
The method checks the coordinates of obj
passed to it as a parameter and limits the character component from visiting the obj
’s ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy