- Home /
GameObject transform relative camera
using UnityEngine;
using System.Collections;
public class SCR_PLAYER_MOV : MonoBehaviour
{
public int playerSpeed = 10;
// Use this for initialization
void Start()
{}
// Update is called once per frame
void Update()
{
float left = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;
float right = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
float amountToMove = Input.GetAxisRaw("Horizontal") * playerSpeed * Time.deltaTime;
transform.Translate(Vector3.right * amountToMove);
if (transform.position.x <= left)
{
transform.position = new Vector3(left, transform.position.y, transform.position.z);
}
else if (transform.position.x >= right)
{
transform.position = new Vector3(right, transform.position.y, transform.position.z);
}
}
}
I'm trying to get the gameobject to be restrained at the boundaries of the main camera, but it clips past it (I used a mediocre solution with a another gameobject and hardcoding). I'm also looking for a solution that keeps the object within the limit relative to the resolution and aspect ratio.
I'm not looking for someone to give me the full code, just enough for me to solve the problem.
If you are talking about the fact that 1/2 of your object is not visible, the reason is that you are checking the center point of the object against the viewport bounds. You can use it's shape to generate two test positions (one for the left edge, one for the right edge), and use logic similar to what you have above. If you need a more general solution, you can use Renderer.bounds to generate the eight points of the bounding box of the object and test them to make sure all eight are visible (or move it so they are).
Your answer
Follow this Question
Related Questions
getting the position of player for the minimap to follow 1 Answer
Distribute terrain in zones 3 Answers
C# 2d Spawn Randomly along Camera Borders 1 Answer
Instantiate cube on network 0 Answers