Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

2D motion help

Discussion in 'Scripting' started by unitybeginner101, Jun 11, 2015.

  1. unitybeginner101

    unitybeginner101

    Joined:
    Jun 30, 2014
    Posts:
    1
    I have written the following script with the intention of having an object moving back and forth on the Y axis. But instead of moving on only the Y, it is moving on a combination of an X and Y. If you could help, that would be great!

    using UnityEngine;
    using System.Collections;

    public class EnemyMovement : MonoBehaviour {


    public float min=2f;
    public float max=3f;
    public float movement=20;
    // Use this for initialization
    void Start () {

    min=transform.position.x;
    max=transform.position.x+movement;

    }

    // Update is called once per frame
    void Update () {


    transform.position =new Vector3(Mathf.PingPong(Time.time*2,max-min)+min, transform.position.y, transform.position.z);

    }
    }
     
  2. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    Bit confused, you want to move it on the Y axis, but you are changing the x component of the vector?

    Also creating a new vector3 every frame is a sure way to force the garbage collector to run. Try:

    // at the top of your class;
    Vector3 pos;

    //in update
    pos=tranform.position;
    pos.y = Mathf.PingPong(Time.time*2,max-min)+min;
    transform.position = pos;

    Also, also - is this frame rate independent? Seems like you might need a * Time.deltaTime in there somewhere?