- Home /
Question by
LazyBassTurd · Jul 28, 2013 at 02:13 PM ·
c#rotationlookat
Rotate/Orbit around an object to look at another object C#
Hi,
I have 3 objects a ship, turret and target. I would like the turret to be within a fixed orbit around the outside of the ship but, still be able to move within the orbit to look at targets.
I have the code to rotate the turret around the ship using keys but, can't figure out a way to get the turret to move around the ship towards a target automatically. (I'm a C# noob btw)
using UnityEngine;
using System.Collections;
public class Orbit : MonoBehaviour {
float rotateSpeed = 100;
Transform theShip;
void Start()
{
theShip = transform.parent;
}
void Update ()
{
if(Input.GetKey(KeyCode.K))
{
Rotate(-1);
}
if (Input.GetKey(KeyCode.L))
{
Rotate(1);
}
}
void Rotate(int whichWay)
{
transform.RotateAround(theShip.position, new Vector3(0, 0, whichWay), rotateSpeed * Time.deltaTime); // (1 is left) (-1 is right)
}
}
rotate.png
(26.4 kB)
Comment
Answer by Orlando Bascunan · Jul 28, 2013 at 02:48 PM
Hello!
Add a GameObject named target to your scene and this should work
using UnityEngine;
using System.Collections;
public class Orbit : MonoBehaviour {
float rotateSpeed = 100;
Transform theShip;
GameObject target;
void Start()
{
theShip = transform.parent;
target = GameObject.Find("target");
}
void Update ()
{
if(Input.GetKey(KeyCode.K))
{
Rotate(-1);
}
if (Input.GetKey(KeyCode.L))
{
Rotate(1);
}
}
void Rotate(int whichWay)
{
transform.RotateAround(theShip.position, new Vector3(0, 0, whichWay), rotateSpeed * Time.deltaTime); // (1 is left) (-1 is right)
transform.LookAt( target.transform.position );
}
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Change output rotation of this Lookat script? 0 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
slowly rotate a object *need quick fix* 0 Answers