- Home /
How to keep player in bounds?
I am making a top down space shooter, in the vein of games like R-Type. I have the player moving just fine, however I am having trouble keeping them within the bounds of the level. If anyone could give me tips on what I am doing wrong it would be greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour {
float maxSpeed = 5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// returns a float from -1.0 to 1.0
// move player forward and backward
Vector3 pos = transform.position;
//
pos.y += Input.GetAxis("Vertical") * maxSpeed * Time.deltaTime;
transform.position = pos;
// move player left and right
pos.x += Input.GetAxis("Horizontal") * maxSpeed * Time.deltaTime;
transform.position = pos;
// RESTRICT player to camer boundries
if(pos.y >= Camera.main.orthographicSize)
{
pos.y = Camera.main.orthographicSize;
}
}
}
Answer by OrbitalTech · Dec 04, 2017 at 11:43 PM
The orthographicSize is half the size of the vertical viewing volume. The horizontal size of the viewing volume depends on the aspect ratio. This is not what you're looking for. A quick look around finds this: https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
if (pos.y >= Camera.ScreenToWorldPoint(new Vector3(Camera.pixelWidth,Camera.pixelHeight, 0f)).y {
pos.y = Camera.ScreenToWorldPoint(new Vector3(Camera.pixelWidth,Camera.pixelHeight, 0f)).y;
}
I would recommend that you adjust that code to be prettier, but it is in full to make it easier to understand.
It may also be important for you to make sure that your camera is in Orthographic mode. You can do this in the inspector or alternatively: m_OrthographicCamera.orthographic = true;
.
If i've made a mistake (which is more than likely), you should be able to figure it out using the ScreenToWorldPoint link I gave.
Your answer
Follow this Question
Related Questions
How to remove a specific prefab from a List? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I move camera towards the mouse while anchoring it to the player? 0 Answers
How would one go about making an asteroid field in a circle around an empty object in 2D? 0 Answers