Moving Objects thats not 0 on the x-axis

Okay, I have no idea what is wrong but every time I put this script on an object no matter where it is, it always goes back to zero on the x-axis when I go to playtest. I’m trying to get an object to move back and forth on the x-axis but not only on zero.

using UnityEngine;
using System.Collections;

public class MoverBlockerMovement : MonoBehaviour
{
    public float speed = 2f;
    void Update()
    {
        transform.position = new Vector3(Mathf.PingPong(Time.time * speed, 4), transform.position.y, transform.position.z);
    }

}

Hi,

Use Debug.Log in the loop to see which positions the transform gets in each frame. Perhaps x is just flipping between 4, and 2* 0.02, or not running at all?

Cache the starting X position value in Start(), then add the results of your PingPong to that original value.

Okay, I’ve been having trouble trying to store the X position in start, mostly because i just dont know how to do it, but i thought of adding the X position to mathf.pingpong so like

using UnityEngine;
using System.Collections;

public class MoverBlockerMovement : MonoBehaviour
{
    public float speed = 2;

    void start()
    {

    }


    void Update()
    {
        transform.position = new Vector3(transform.position.x + Mathf.PingPong(Time.time * speed, 4), transform.position.y, transform.position.z);
    }

}

but doing this made the objects flew right off the map so that was not working but it did not reset the x position on the 0 on the x axis

Also sorry for taking a while for a response

Try

float xStart = transform.position.x;

in void Start(), it’s case sensitive.

1 Like

Okay so I’ve added it to the start function but now I’m confused on how to add it as I’ve been trying for a little while and just am not getting it down, how would I add the PingPong to the original value?

Try something like this:

   public float speed = 2;
   private Vector3 startingPosition;

   void Start()
   {
       startingPosition = transform.position;
   }

   void Update()
   {
       transform.position = new Vector3(startingPosition.x + Mathf.PingPong(Time.time * speed, 4), transform.position.y, transform.position.z);
   }
1 Like

Thank you! I understand this now a lot better after seeing it, thank you for the help guys.

1 Like