Jump to content

Collision Trouble


OhNoItsATornahdo
 Share

Recommended Posts

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...