0
\$\begingroup\$

I am creating an endless runner with a flying character.

I want to lock any movement in the x axis so that the character object can only move up and down but still move forward through the scene. I have looked into freezing axes and joints, but this stops the forward movement.

Is it possible to edit the below to lock the x axis for character movement only, or is there a setting where i can apply this?

using UnityEngine;
using System.Collections;

public class moveupdown : MonoBehaviour {
    public Vector2 velocity;
    public float uservelocity;
    public Rigidbody2D rb2D;

    void Start() {
        rb2D = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate() {        

        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Moved) {
            Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;

            rb2D.MovePosition (rb2D.position + touchDeltaPosition * Time.fixedDeltaTime / uservelocity);

        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ I have tried rigid body constraints too, but they stop any x axis movement, meaning my character is not able to move through the scene at all \$\endgroup\$ – Gary Jul 14 '15 at 22:07
1
\$\begingroup\$

Don't take deltaPosition.x value:

Vector2 touchDeltaPosition = new Vector2(0, Input.GetTouch(0).deltaPosition.y);
\$\endgroup\$
  • \$\begingroup\$ Thanks Adrian, I am now not able to move along x axis, great! However, x movement freezes when i move the character up and down, once i remove my finger he starts moving along x again. \$\endgroup\$ – Gary Jul 15 '15 at 6:12
  • \$\begingroup\$ @Gary If you add this delta position to the calculated x delta per frame, you should will not be frozen in the x axis. \$\endgroup\$ – MichaelHouse Jul 15 '15 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.