Stop movement at edge of screen! 2d shooter

Hi! I’m trying to learn to make a shooter!

I already made the player movement!

And, here’s how it gets weird!!

I want the movement stopped at the edge of the screen!!

Here’s what I did!!

  • box collider on player

  • I added a cube at the edge of the screen to restrict movement(box collider)!

  • Added rigidbody to player cube!

  • Disabled gravity

  • Freezed x,y,z position and rotation of both!

Now when I run the game and with the player if I hit the screen limiter…

It goes straight through it!

Probably A basic error on collision!!

But I wanted to know is there any btter way to restrict movement at edge of the screen for 2d shooter game!!

We need to see some of your code and perhaps have a better description to figure out why your collision detection is not working, but there are other ways to restrict movement. Viewport coordinates go from (0,0) in the lower left to (1,1) in the upper right. We can convert the world position to Viewport coordinates, clamp the result to some range, then convert back to world coordinates. After you done the character move, add these lines:

var pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp(pos.x, 0.1, 0.9);
pos.y = Mathf.Clamp(pos.y, 0.1, 0.9);
transform.position = Camera.main.ViewportToWorldPoint(pos);

Note these lines clamp the pivot point, so the clamp is a bit inside the 0 to 1 range. You will need to adjust the ‘0.1’ and ‘0.9’ as appropriate to the size of your character.

Hello,

You don’t need the physics engine at all to accomplish that, just “limit” the player movements.

For example, let’s say you want to limit movement on X axis from -4.3 to 4.3 and on Y axis from -2.7 to 2.7:

// X axis
if (transform.position.x <= -4.3f) {
	transform.position = new Vector2(-4.3f, transform.position.y);
} else if (transform.position.x >= 4.3f) {
	transform.position = new Vector2(4.3f, transform.position.y);
}

// Y axis
if (transform.position.y <= -2.7f) {
	transform.position = new Vector2(transform.position.x, -2.7f);
} else if (transform.position.y >= 2.7f) {
	transform.position = new Vector2(transform.position.x, 2.7f);
}

You just need to check when the player reaches the limits and put it back there.

Hope it helps!

There’s (the start of a) a good tutorial on making a basic Pong game using the Unity2D components. Find it here: 1. How to make a 2D Game - Unity 4.3 Tutorial - YouTube

I don’t know what’s wrong with your scene, but if you follow that tutorial you might find something out you didn’t know.

Always put your input-related code in Update().

@AndrewRyan

You’re right, update() it is.