Вы должны ознакомиться с Руководствами по мобильному касанию , Руководством по мобильному касанию и Input.GetTouch . Короче говоря: вы должны получить касание, сохранить начальную позицию и сравнить ее с текущими позициями.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 300f;
public float sidewaysForce = 200f;
private Vector2 initialPosition;
// Update is called once per frame
void Update()
{
// are you sure that you want to become faster and faster?
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if(Input.touchCount == 1)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
initialPosition = touch.position;
}
else if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
// get the moved direction compared to the initial touch position
var direction = touch.position - initialPosition;
// get the signed x direction
// if(direction.x >= 0) 1 else -1
var signedDirection = Mathf.Sign(direction.x);
// are you sure you want to become faster over time?
rb.AddForce(sidewaysForce * signedDirection * Time.deltaTime, 0, 0);
}
}
}
}
Примечание: это всегда сравнивается с начальной позицией касания => вы не идете в другом направлении, пока вы не
- Переместить касание в исходное положение в другом направлении
- И поскольку вы используете
AddForce
, ждите столько же времени, сколько вы добавили в другом направлении
Возможно, вам лучше сравнивать только предыдущую позицию касания, а не исходную:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 300f;
public float sidewaysForce = 200f;
private Vector2 lastPosition;
// Update is called once per frame
void Update()
{
// are you sure that you want to become faster and faster?
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if(Input.touchCount == 1)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
lastPosition = touch.position;
}
if(touch.phase == TouchPhase.Moved)
{
// get the moved direction compared to the initial touch position
var direction = touch.position - lastPosition ;
// get the signed x direction
// if(direction.x >= 0) 1 else -1
var signedDirection = Mathf.Sign(direction.x);
// are you sure you want to become faster over time?
rb.AddForce(sidewaysForce * signedDirection * Time.deltaTime, 0, 0);
lastPosition = touch.position;
}
}
}
}
Теперь вам все равно придется провести столько же времени ... оно не учитывает пройденное расстояние. Так что, возможно, вместо этого вы должны использовать это:
// get the moved direction compared to the initial touch position
var direction = touch.position - lastPosition ;
// are you sure you want to become faster over time?
rb.AddForce(sidewaysForce * direction.x * Time.deltaTime, 0, 0);
так что чем больше вы проводите, тем больше силы добавляется.