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!!!