How to add collisions to a sprite?

Hi, I’m trying to make a game, and for the life of me I cannot figure out how to get the player to collide with a wall and stop moving, I need the sprite, when it hits a wall or other boundary, to stop moving and not walk off of the screen.

So far, I’ve tried adding colliders to the sprites but I can’t seem to figure it out, and since the background I made is also a sprite (because I’m unsure of how to add it to the game otherwise) the collider takes up the whole screen once added, I’m new to programming so help would be very much appreciated!!

(here’s a link to the project if anyone needed to look at it, Game Lab - Code.org)

Greetings @BunnieSmiles,

This depends on what your trying to do, sprites have prebuilt collisions however if you just want to stop the player from moving out of the screen a few && statements should implement what your trying to do I’ll link one of the two that you’ll probably want to implement

if (keyDown("a") && Aoi.x - Aoi.getScaledWidth() / 2 > 0) {
    Aoi.setAnimation("Aoi Walk left");
    Aoi.x -= 4;
  }

Hope this helps

@BunnieSmiles ,

There is a helper block of code called createEdgeSprites. If you use it, you can set a collision on those sprites so characters bounce off of them or just stop.

Let us know if we can help further, but I think a combination of the above is probably the most simple way to handle this issue.

Good luck!

Mike

Thank you!! I’ll try this and see if it works!! <3

Thank you!! I’ll try this :slight_smile:

I agree more with @mwood as this is a much simpler approach than of what @varrience did.
You just have to declare

createEdgeSprites();

Then in the draw function you put:

Aoi.collide(edges); // you can also do topEdge bottomEdge rightEdge or leftEdge if you wanna be specific. 
2 Likes