- Home /
Question by
haimmoshe · Jun 27, 2017 at 09:29 PM ·
c#scripting problemscript.
How can i keep the transform height while it's moving ?
bool flying = false; // shows when FlyTo is running
// coroutine that moves to the specified point:
IEnumerator FlyTo(Vector3 targetPos)
{
flying = true; // flying is true while moving to the target
Vector3 startPos = transform.position;
Vector3 dir = targetPos - startPos;
float distTotal = dir.magnitude;
dir /= distTotal; // normalize vector dir
// calculate accDist even for short distances
float accDist = Mathf.Min(accDistance, distTotal / 2);
do
{
float dist1 = Vector3.Distance(transform.position, startPos);
float dist2 = distTotal - dist1;
float speed = maxVel; // assume cruise speed
if (dist1 < accDist)
{ // but if in acceleration range...
// accelerate from startVel to maxVel
speed = Mathf.Lerp(startVel, maxVel, dist1 / accDist);
}
else
if (dist2 < accDist)
{ // or in deceleration range...
// fall from maxVel to stopVel
speed = Mathf.Lerp(stopVel, maxVel, dist2 / accDist);
}
// move according to current speed:
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
yield return 0; // let Unity breathe till next frame
} while (transform.position != targetPos); // finish when target reached
flying = false; // shows that flight has finished
}
I want that the transform will get to the targetPos but above it in the air. If the transform height at start for example is 200 then i want it will get to the targetPos at height 200. Now when it's getting to the targetPos it's in height 0.
Maybe i need to use Raycast hit ? Not sure how to do it.
Comment
Answer by haimmoshe · Jun 27, 2017 at 10:41 PM
Working solution:
Vector3 pos = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
pos.y = lastPos.y;
transform.position = pos;