0
\$\begingroup\$

I am trying to develop an endless runner where there is a sphere as the player and it is moving left and right following the position of a finger on a touch screen. However, when I try to do this I cannot get the player to lock on the Y-axis. I want a constant force that speeds up overtime which I have using the constant force 2d supplied by unity. I have two versions of code, the first follows the finger but the player is able to move up and down as well:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour
{
    public GameObject character;
    public float speed = 500.0f;

    void Start()
    {
        Input.multiTouchEnabled = false;
    }

    void Update()
    {
        if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 target = Camera.main.ScreenToWorldPoint(
                              new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            character.transform.Translate(Vector3.MoveTowards(character.transform.position, 
                              target, speed * Time.deltaTime) - character.transform.position);
    }
}

The second code I have allows the player to move left and right by tapping rather than following but is still sloppy:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float sidewaysForce = 500f;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        {
            foreach (Touch touch in Input.touches)
            {
                if (touch.position.x < Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * -1, rb.velocity.y);
                }
                if (touch.position.x > Screen.width / 2)
                {
                    rb.velocity = new Vector2(sidewaysForce * +1, rb.velocity.y);
                }
            }
        }
    }
}

Any help on this would be awesome Thanks!!!

\$\endgroup\$
0
\$\begingroup\$

in 2d horizon is X axis. for restriction you can simple put a restricting object or read borders of your camera.assume you have a minX and minY empty objects. so you will have:

    [SerializeField] private Transform minX;
    [SerializeField] private Transform maxX;
void Update()
{
  if (transform.position.x < minX.position.x) { transform.position = new Vector3(minX.position.x,transform.position.y,transform.position.z); }
  if (transform.position.x > maxX.position.x) { transform.position = new Vector3(maxX.position.x, transform.position.y, transform.position.z); }
}
\$\endgroup\$

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.