我用Unity和C#做了一个3D游戏。我不知道如何通过在移动屏幕上滑动来左右对象(播放器)控制。
这是我的C#代码:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 300f;
public float sidewaysForce = 200f;
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetAxis("Horizontal") > 0.1)
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
}
if (Input.GetAxis("Horizontal") < -0.1)
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
}
}
}
你应该看看Mobile Touch Tutorials,Mobile Touch Manual和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);
所以你刷的越多,所添加的力就越多。