- Home /
Limit distance from center
The following code let's my ship move around a spherical world. It works great except when it collides with an collider. If head on it will float up into space.
How can I prevent this behavior? I tried clamping the magnitude and combining the resulting vector with a forwards vector and putting that into rigidBody.MovePosition, but that makes my ship immobile.
using UnityEngine;
using System.Collections;
public class MovementTest : MonoBehaviour {
[SerializeField]private float turnSpeed = 60;
[SerializeField]private float forwardSpeed = 40;
private Rigidbody mRigidBody;
private float distance;
// Use this for initialization
void Start () {
mRigidBody = rigidbody;
distance = Vector3.Distance(mRigidBody.position, Vector3.zero);
}
void FixedUpdate ()
{
//Forward speed
mRigidBody.velocity = transform.forward * Time.deltaTime * forwardSpeed;
//Calculate the up vector
Vector3 surfaceUp = mRigidBody.position - Vector3.zero;
//Set the current rotation of the rigidBody
Quaternion surfaceUpRotation = mRigidBody.rotation;
//Set the angle to 90 degress
surfaceUpRotation.SetLookRotation(surfaceUp, -transform.forward);
surfaceUpRotation *= Quaternion.Euler(90,0,0);
//get a rotation for steering
Quaternion rot = Quaternion.identity;
if(Input.GetKey(KeyCode.LeftArrow) )
rot = Quaternion.Euler( transform.up * Time.deltaTime * -turnSpeed );
else if(Input.GetKey(KeyCode.RightArrow))
rot = Quaternion.Euler( transform.up * Time.deltaTime * turnSpeed );
//multiply it with the surface rotation to add them.
mRigidBody.MoveRotation( surfaceUpRotation * rot );
}
}
Comment