Trying to wrap up a tiny student project and I noticed that my player is gets stuck at the edges of the screen for a tiny bit. Eventually he can pull away and move as normal. I’m sure it has to do with how I coded my game. Do to the short deadline of the project I didn’t have time to teach myself about “clamping” the player’s movement and just hard-coded the boundaries as the level is static (no scrolling or camera movement in my 2D game).
After the project is done I will definitely look into the proper way to handle this, but right now I have a deadline fast approaching. Despite this I thought I would still see if there was a simple fix within my given code, rather than just putting box colliders around the edge of the stage to prevent the player that way (cringes).
Here is my current Player controller. I didn’t have to worry about stopping the player at the bottom of the screen because there is ground that has a collider on it to stop him. As you can probably tell I’m still rather new to Unity:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private float speed = 3;
private Rigidbody rb;
private float screenLeft = 1.2f;
private float screenRight = 15.2f;
private float screenTop = 7.7f;
private Vector3 pos;
public Transform bulletSpawn;
public GameObject bullet;
public AudioClip shootSound;
private AudioSource source;
private float volLowRange = .5f;
private float volHighRange = 1.0f;
public SoundManager soundManager;
void Awake ()
{
source = GetComponent<AudioSource>();
}
// Use this for initialization
void Start ()
{
rb = GetComponent<Rigidbody> ();
}
void Update ()
{
Physics.Raycast(bulletSpawn.position, bulletSpawn.right, 50f);
Debug.DrawRay(bulletSpawn.position, bulletSpawn.right);
pos = transform.position;
//CODE TO STOP PLAYER AT EDGES OF SCREEN
if (transform.position.x < screenLeft)
{
pos.x = screenLeft;
transform.position = pos;
}
else if (transform.position.x > screenRight)
{
pos.x = screenRight;
transform.position = pos;
}
else if (transform.position.y > screenTop)
{
pos.y = screenTop;
transform.position = pos;
}
if (Input.GetButtonDown("Fire1"))
{
Instantiate (bullet, bulletSpawn.position, bulletSpawn.rotation);
float vol = Random.Range(volLowRange, volHighRange);
source.PlayOneShot(shootSound, vol);
}
}
// Update is called once per frame
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
rb.AddForce (movement * speed );
}
}