我是统一和游戏开发的新手,所以我尝试制作游戏。一切都很顺利,直到我考虑将游戏从 PC 更改为 Android。
PC 上的运动运行良好,但我似乎找不到任何代码用于 Android 的相同运动。
这就是我用于 PC 运动的东西
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewayForce = 500f;
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if ( Input.GetKey("d") )
{
rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
这就是我用于 android 运动的方法,但唯一的问题是它不会前进,玩家甚至不会移动。该脚本以某种方式移动玩家所在的平台。
public class PlayerMovANDROID : MonoBehaviour
{
// Use this for initialization
GameObject hitObj;
RaycastHit hit;
private float speed = 1;
void Start()
{
}
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
switch (touch.phase)
{
case TouchPhase.Began:
Ray ray = Camera.main.ScreenPointToRay(touch.position);
if (Physics.Raycast(ray, out hit, 10))
{
hitObj = hit.collider.gameObject;
}
break;
case TouchPhase.Moved:
// If the finger is on the screen, move the object smoothly to the touch position
float step = speed * Time.deltaTime; // calculate distance to move
if (hitObj != null)
hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, hitObj.transform.position.z));
break;
}
}
}
}