- Home /
Lock player movement within screen bounds
I am making a simple 2D game and this is my player movement script:
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(new Vector3(horizontalInput, 0, 0) * Time.deltaTime * speed);
}
}
I, now want to lock this movement within screen bounds. The code for the same is:
public class Boundaries : MonoBehaviour
{
private Vector2 screenBounds;
private float objectWidth;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height,Camera.main.transform.position.z));
objectWidth = GetComponent<SpriteRenderer>().bounds.size.x/2;
}
void LateUpdate()
{
Vector2 viewPos = transform.position;
viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + objectWidth, screenBounds.x*-1 - objectWidth);
transform.position = viewPos;
}
}
After attaching this script to Player gameobject, I notice the following error:
The player gameobject continues to blink on the left and right side(as in the image) in Scene view. What could be the reason for this and how to correct to limit the player movement?
Answer by Nefisto · Jun 08, 2021 at 10:04 PM
@pranshi112 IDK if you still need help, but hope that this helps. I make it clamp itself to the camera area but you can easily change it's to some object position or constant value if you need
using System;
using UnityEngine;
public class Ball : MonoBehaviour
{
public float moveSpeed = 5f;
private float xMin, xMax;
private float yMin, yMax;
private void Start()
{
var spriteSize = GetComponent<SpriteRenderer>().bounds.size.x * .5f; // Working with a simple box here, adapt to you necessity
var cam = Camera.main;// Camera component to get their size, if this change in runtime make sure to update values
var camHeight = cam.orthographicSize;
var camWidth = cam.orthographicSize * cam.aspect;
yMin = -camHeight + spriteSize; // lower bound
yMax = camHeight - spriteSize; // upper bound
xMin = -camWidth + spriteSize; // left bound
xMax = camWidth - spriteSize; // right bound
}
private void Update()
{
// Get buttons
var ver = Input.GetAxis("Vertical");
var hor = Input.GetAxis("Horizontal");
// Calculate movement direction
var direction = new Vector2(hor, ver).normalized;
direction *= moveSpeed * Time.deltaTime; // apply speed
var xValidPosition = Mathf.Clamp(transform.position.x + direction.x, xMin, xMax);
var yValidPosition = Mathf.Clamp(transform.position.y + direction.y, yMin, yMax);
transform.position = new Vector3(xValidPosition, yValidPosition, 0f);
}
}
Answer by brian1gramm1 · Jun 06, 2021 at 11:06 PM
I read the answer to this question in a book I bought, not sure if I'm allowed to show his solution or not. But he uses Camera.WorldToViewportPoint to see if the player ship is near the viewing area. https://docs.unity3d.com/540/Documentation/ScriptReference/Camera.WorldToViewportPoint.html