OhNoItsATornahdo Posted September 8, 2017 Share Posted September 8, 2017 So I'm making a prototype for a game, and I want to add a collision system to it. I have the detection part down: function checkCollision(rect1, rect2) { if (rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y) { } } And I don't want the player to move past the rectangle it's colliding with. If I were to type to type 'player.x += 0' or 'player.speed = 0', it would just stop the player from moving regardless if I press WASD. How would I make it so that my player can't move through objects? Quote Link to comment Share on other sites More sharing options...
hotfeet Posted September 9, 2017 Share Posted September 9, 2017 here's a quick fiddle that shows that cool minkowski shizzle. i didn't add keyboard controls but just mouse over to move the rect you can just adapt from that. the relevant code is really just the function rectCollision(rect1, rect2) https://jsfiddle.net/hotfeet/euobdLvy/ OhNoItsATornahdo and Taz 1 1 Quote Link to comment Share on other sites More sharing options...
OhNoItsATornahdo Posted September 9, 2017 Author Share Posted September 9, 2017 16 hours ago, hotfeet said: here's a quick fiddle that shows that cool minkowski shizzle. i didn't add keyboard controls but just mouse over to move the rect you can just adapt from that. the relevant code is really just the function rectCollision(rect1, rect2) https://jsfiddle.net/hotfeet/euobdLvy/ This works really well! But there is a minor problem: when my player collides with the other object from any direction and I press WASD, the player slightly goes into and out of the object. Not by much, thankfully. Quote Link to comment Share on other sites More sharing options...
hotfeet Posted September 9, 2017 Share Posted September 9, 2017 21 minutes ago, OhNoItsATornahdo said: This works really well! But there is a minor problem: when my player collides with the other object from any direction and I press WASD, the player slightly goes into and out of the object. Not by much, thankfully. it's difficult to know what might be the issue without seeing some code. it does sound like tunneling and can be a bull to wrangle at times. you might need more advanced collision handling than what was in the fiddle. i just offered it as a simple solution and it works for a lot of things. best of luck. OhNoItsATornahdo 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.