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.
Try something like this:
void Update() {
transform.position = target.TransformPoint(new Vector3(0,2,-10));
transform.LookAt(target);
}
Incidentally, since it’s your first day with Unity, perhaps it’s not too late for me to recommend you ditch UnityScript (which is a JavaScript-ish layer on top of a C# API that isn’t really either one), and code in C#. The C# compiler does a much better job of catching common mistakes, and is generally more widely used and better supported. Of course that’s IMHO, YMMV, etc.
Oops, sorry, I was in too much of a rush on the previous post and didn’t catch the important point, which is you want to be able to rotate around the object with the keys.
For that, the easiest way may be to let Unity do all the work for you. Set your scene up like this:
-
Create an empty GameObject inside your target object, and call it CamHolder. IMPORTANT: make sure that CamHolder has the same position in the inspector as your target object! (You can copy and apply the Transform property to easily ensure this.)
-
Stick your Camera inside of CamHolder. Position it however you like, so it’s looking at the target the way you want.
-
Put a script like your original onto CamHolder, but forget about “target”; just have it rotate itself (i.e. just call transform.Rotate).
So, wherever the target goes, CamHolder goes too because it’s a child object, and your camera goes along because it’s a child of that. And when CamHolder rotates, it rotates and moves your camera, again because it’s a child object.
This makes it very easy to tweak the relative position & angle of the camera however you like, without having to touch the code.