- Home /
Restricting movement on the vertical axis
I am using the following orbiting script:
var otherObject : GameObject;
var distance;
function Start () {
}
function Update () {
distance = Vector3.Distance(this.transform.position, otherObject.transform.position);
if(distance !=50) {
Debug.Log(distance);
distance = 50;
transform.position = (transform.position - otherObject.transform.position).normalized * distance + otherObject.transform.position;
}
var somePos : Vector3 = otherObject.transform.position;
transform.RotateAround (somePos, transform.up, 20 * Time.deltaTime);
}
This is doing what I want it to do, except for that when I decrease the distance between myself and the object this script is attached to, it moves up into the air instead of away from me. How do I fix this?
Answer by ScroodgeM · Jul 29, 2012 at 07:59 PM
this script will move object like truck's trail when truck goes backward. so, if your other object's height is lower then this object, then this object will go upwards when you move towards it.
solution 1: clamp Y component of all calculations and height will no gives any affect
solution 2: as i understand you just rotating this transform around 'otherObject' with a constant distance 50. i'm sure the best way to achieve this is to attach this object to 'otherObject' as a child and just rotate it around 'otherObject'. distance will kept without any manual actions and relative height will also be constant.
solution 3:
using UnityEngine; using System.Collections; public class Rotator : MonoBehaviour { public Transform rotateAroundObject; public float rotationSpeed = 20f; public float keepDistance = 50f; float rotationAngle = 0f; void Update() { rotationAngle = Mathf.Repeat(rotationAngle + Time.deltaTime * rotationSpeed, 360f); Quaternion rotationNeed = Quaternion.AngleAxis(rotationAngle, Vector3.up); transform.position = rotateAroundObject.position + rotationNeed * Vector3.forward * keepDistance; } }
the problem with solution 2 is that the object being orbited is the player, and when the player turns, the object turns with them. How would i clamp the Y component?
is this javascript? Sorry if i was not clear, I dont really know many other languages besides java and javascript (and i dont know javascript that well either)
no, this is C#, just save these lines to 'Rotator.cs' in your project folder
And then attach the script to the same object that is rotating around the player?
Your answer
![](https://koobas.hobune.stream/wayback/20220613074843im_/https://answers.unity.com/themes/thub/images/avi.jpg)