Search code examples
unity-game-enginesmoothing

How change the Y position of moving forward spaceship in Unity 3D


i have start a project in unity 3d.I want to make a spaceship that moving forward,but when i pressed the ArrowUp then i want to change its y postion to ( currentpos+ 1.5 ) but i want this smoothly. this is my code

transform.position += transform.forward * Time.deltaTime * 10f;

if (Input.GetKey (KeyCode.UpArrow))
transform.position = new Vector3 (transform.position.x, 5f, 
transform.position.z);

through the above code the Y position of object can b changed but it work so fast and i want to make it smooth. so please help me.


Solution

  • I think the best solution to your problem is to use Mathf.SmoothDamp.

    Example:

    private float targetY = 0f;
    private float verticalVelocity = 0f;
    private const float smoothTime = 1f;
    
    private void Update()
    {
        transform.position += transform.forward * Time.deltaTime * 10f;
    
        if (Input.GetKey(KeyCode.UpArrow))
        {
            targetY = 5f;
        }
    
        float y = Mathf.SmoothDamp(transform.position.y, targetY, ref verticalVelocity, smoothTime);
        transform.position = new Vector3 (transform.position.x, y, transform.position.z);
    
    }
    

    This example will smoothly change the y coordinate to 5 over the course of 1 second (you can change the smoothTime constant for a different time).