- Home /
Movement with camera and rotation of objects
Hi folks! I'm currently developing a straight forward game, in which I want the camera to move and be able to rotate (This part is not a problem), but I want 2 arrows in the bottom right corner at all times, that indicate the X, Y and Z axis the player can move along.
-
What I'm trying to do:
Get 2 arrows in the bottom right corner, and be able to click those 2 arrows to move the player around.(The clicking and moving part is done).
-
What I've tried:
1) Using an easy Test-If-Camera-Is-At-A-Different-Location script, and then move the objects accordingly (This has the problem that whenever I rotate the camera, the objects stay in the same position, and go off-screen)
2) Using a canvas, so the objects can rotate along with the camera (This had the problem that when I moved the player, the objects wouldn't come along or have a delay, or when I made the object big so they were basically stuck to the canvas, they clipped through all the terrain, which was foreseeable)
Any help would be appreciated! Thanks in advance!
A simplified version of what I want to achieve. This gives an idea of how I want the arrows to be positioned, at all times.
Answer by goddatr · May 09, 2018 at 12:13 PM
If I correctly understand what you want is red and green objects always be on the bottom left of your screen ?
Then you should just make them child of your camera. This way if you move or rotate your camera they will stay at the same relative position for your camera
Yes, although this could work for positioning the objects, I don't want the objects to rotate, meaning if I rotate/pan the camera, the objects should stay in the same orientation, and not relative to the camera.
If you attach the arrows to an empty GameObject as their parent, you can easily manipulate it in either of two ways.
If you *DO* parent the empty to the camera, apply an inverted rotation to it whenever the camera rotates:
arrowBase.rotation = Quaternion.Inverse(mainCam.transform.rotation);
Alternately, if you *DON'T* parent it to the camera, position it how you want, save that offset during Start(), and move its position whenever the camera moves or rotates.
Vector3 offset;
void Start()
{
offset = mainCam.transform.TransformPoint(arrowBase.position);
}
void Update()
{
arrowBase.position = mainCam.transform.TransformPoint(offset);
}
Although is does not seem to work, as the objects rotate far more than they should, it inspired me to do some of my own digging into quaternions and I eventually found a solution.
Note that I have this script sitting on my main camera, which has a child named arrows, in which all my arrows are located.
using UnityEngine;
public class ArrowScript : $$anonymous$$onoBehaviour
{
public GameObject arrows;
public Vector3 offset;
private void LateUpdate()
{
arrows.transform.rotation = Quaternion.LookRotation(offset);
}
}