- Home /
Rotate camera around moving object
Hi so I started today with Unity and I have some big progress. however I have struggle to make rotation about moving object and follow it at the same time. My code so far:
function Start () {
}
var gObj = GameObject.Find("ball");
var target : Transform;
var rotationspeed = 40;
function Update () {
transform.LookAt(target);
if (Input.GetKey(KeyCode.A)){
transform.RotateAround (gObj.transform.position,Vector2.up,rotationspeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D)){
transform.RotateAround (gObj.transform.position,Vector2.up,-rotationspeed * Time.deltaTime);
}
}
So with that code I make using A and D to rotate around ball and Looking At it at same time. Now in my case ball will move around and Camera suppost to follow it and keep same distance from ball all the time.
Answer by OrbitGames · Jul 30, 2015 at 07:18 PM
if you want to do it using a script, first you need to rotate the Camera around the y axis based on key Input, then set its position to the gameObjects position - transform.forward * the distance between the GOs In code it should look something like this(sorry for c#, untested)
if (Input.GetKey(KeyCode.A)){
tranform.Rotate(0,rotationSpeed*Time.deltaTime,0);
}
if (Input.GetKey(KeyCode.D)){
tranform.Rotate(0,-rotationSpeed*Time.deltaTime,0);
}
transform.position = target.position - transform.forward * 15;
Answer by _Gkxd · Jul 30, 2015 at 07:07 PM
While it's possible to do this using scripts, it's probably easier to parent transforms to each other.
The structure of the GameObjects would look something like this:
Ball (Your GameObject)
|-> Pivot Point (Empty GameObject, child of "Ball")
|-> Camera (Your Camera, set position to <0, 0, -1>, rotation to <0, 0, 0>, scale to <1, 1, 1>)
Now, when you want to rotate your camera, rotate the "Pivot Point" GameObject instead. (Try doing this manually in the scene view first.)
The camera will automatically move around the ball. If you want to move your camera away/closer to the center, you can scale the "Pivot Point" GameObject.
Your answer
![](https://koobas.hobune.stream/wayback/20220611233754im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Keyboard rotating - left is stopping object 1 Answer
Cube Rotating & Moving 1 Answer
rotating/moving colliders with or without rigidbodies? 2 Answers
Ball moving only diagonal 0 Answers