- Home /
Unity movement forward doesn't work as expected
firstly i'm sorry for my bad english, i''ll try to explain my problem...
i'm moving my object on a road builded with a primitive plaines, there is also some downhill parth, (like a car that run on a road)
here is my script :
private Transform[] planeArray;
private float speed;
private Quaternion[] _planeRInverse;
private Transform _pvotPlayer;
private void MoveForward ()
{
float moveZ = speed * Time.deltaTime;
_pvotPlayer.transform.position += _pvotPlayer.transform.forward * moveZ;
}
private void SetupPlane()
{
_planeRInverse = new Quaternion[planeArray.Length];
for (int i = 0; i < planeArray.Length; i++)
{
_planeRInverse[i] = Quaternion.Inverse(planeArray[i].rotation);
}
}
private void CheckPosition()
{
Vector3 playerPos = _pvotPlayer.transform.position;
Vector3 v1;
for (int i = 0; i < planeArray.Length; i++)
{
v1 = playerPos - planeArray[i].position;
Vector3 lv1 = _planeRInverse[i] * v1;
float scaleX = planeArray[i].localScale.x;
float scaleZ = planeArray[i].localScale.z;
float vh = 5f * scaleX; // unity plane is of 10.0f
float vf = 5f * scaleZ;
if ( IsBetween(lv1.x,0.0f - vh,0.0f + vh) && IsBetween(lv1.z,0.0f - vf,0.0f + vf))
{
Vector3 dp = playerPos - planeArray[i].position;
dp.y = 0;
Vector3 lp = planeArray[i].rotation * dp;
float fixedY = lp.y + planeArray[i].position.y + 0.2f;
_pvotPlayer.transform.position = new Vector3(_pvotPlayer.transform.position.x,fixedY,_pvotPlayer.transform.position.z);
Vector3 newRot = new Vector3 (planeArray[i].eulerAngles.x,planeArray[i].eulerAngles.y,planeArray[i].eulerAngles.z);
_pvotPlayer.transform.eulerAngles= newRot;
}
}
}
public bool IsBetween(double testValue, double bound1, double bound2)
{
return (testValue >= Mathf.Min(bound1,bound2) && testValue <= Mathf.Max(bound1,bound2));
}
this should fix my player y axis 0.2f upper on the current plane, but doesn't work as i'm expected on downhill i'm getting something like this
anyone know what i'm doing wrong? thank's you in advance
immagine.jpg
(26.6 kB)
Comment
Answer by qobion · Oct 15, 2018 at 06:24 PM
I dont know what's wrong with your code. But for this kind of movement you can simply use raycast to get position and rotate your player to the same direction as plane below.
void Update () {
transform.Translate(Vector3.forward * Time.deltaTime*speed);
RaycastHit ray;
if (Physics.Raycast(transform.position, Vector3.down, out ray, 1))
{
transform.rotation = Quaternion.Lerp(transform.rotation, ray.transform.rotation, Time.deltaTime*speed);
Vector3 pos = ray.point;
pos.y += 0.2f;
transform.position = pos;
}