NoviKorisnikk
NoviKorisnikk

Reputation: 313

How to move object on x axis smoothly?

I want to ask how I can smoothly move object on x axis to left and right ? I want to move exactly only on X axis where z and y axis will stay the same as before the movement. I tried with code:

rb.Transform.Translate(Vector3.right * Time.deltatime * 130);

but that teleports the player i want movement to be fast how much i want. I want to only add on x axis for example if the object is on

0->X
0->Y
0->Z

I want to move to right then x axis need to be = 4,When i want to get left if the object is moved right and its on coordinates (4,0,0) I want to get back to (0,0,0) when press the key to get left. When i want one more field left the coordinates need to be (-4,0,0) I hope someone will get what i want to achieve.

EDIT:

The blue star is player on position , i want to smoothly move to right and left only on x axis where YZ stays the same, on picture is how i want to move, and i want only smoothly movement not teleporting

enter image description here

BLUE IS WHERE THE PLAYER IS AND YELLOW&GREEN STAR IS WHERE PLAYER NEED TO GO WHEN IS GOING TO RIGHT OFC WHEN GOING TO LEFT NEED TO BE ON THE SAME POSITION AGAIN ... Thanks

Upvotes: 0

Views: 2212

Answers (2)

moon cheese
moon cheese

Reputation: 471

Try Vector3.Lerp

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    // Transforms to act as start and end markers for the journey.
    public Transform startMarker;
    public Transform endMarker;

    // Movement speed in units/sec.
    public float speed = 1.0F;

    // Time when the movement started.
    private float startTime;

    // Total distance between the markers.
    private float journeyLength;

    void Start()
    {
        // Keep a note of the time the movement started.
        startTime = Time.time;

        // Calculate the journey length.
        journeyLength = Vector3.Distance(startMarker.position, endMarker.position);
    }

    // Follows the target position like with a spring
    void Update()
    {
        // Distance moved = time * speed.
        float distCovered = (Time.time - startTime) * speed;

        // Fraction of journey completed = current distance divided by total distance.
        float fracJourney = distCovered / journeyLength;

        // Set our position as a fraction of the distance between the markers.
        transform.position = Vector3.Lerp(startMarker.position, endMarker.position, fracJourney);
    }
}

source: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Upvotes: 1

Attersson
Attersson

Reputation: 4876

Every frame, you could create a new Vector3 with the object original z and y and just update the x according to time logic. Then assign this vector to the object transform. This is the simplest way.

Upvotes: 0

Related Questions