我用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);
}
}
}
答案 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
,所以您等待的时间与向另一方向施加力的时间相同也许您应该只比较previos触摸位置,而不是比较初始位置:
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);
所以您滑动的次数越多,施加的力就越大。