[英]Movement Script for a 3D Unity Game Using C# Not Working
我正在尝试使用Rigidbody.MovePosition
创建一个脚本来移动我的 3D 手机游戏的播放器。 下面,我附上了我到目前为止的脚本。 我曾尝试使用 Unity Remote 5 对其进行测试,但使用该应用程序时没有任何反应。 我非常感谢任何关于我应该进行哪些调整以使其适应 function 的建议。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed = 10.0f;
public Rigidbody rb;
public Vector2 movement;
private Touch touch;
void Start()
{
rb = this.gameObject.GetComponent<Rigidbody>();
}
void Update()
{
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter(Vector2 direction)
{
if(Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
rb.MovePosition((Vector2)transform.position + (direction * speed *Time.deltaTime));
}
}
}
}
使用以下建议,我调整了代码,但现在我收到一条错误消息: FixedUpdate() can not take parameters
。
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed = 10.0f;
public Rigidbody rb;
private Vector3 position;
private Touch touch;
private float width;
private float height;
void Start()
{
rb = this.gameObject.GetComponent<Rigidbody>();
width = Screen.width;
height = Screen.height;
}
void FixedUpdate(Vector2 direction)
{
if(Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
Vector2 pos = touch.position;
pos.x = (pos.x - width) / width;
pos.y = (pos.y - height) / height;
position = new Vector3(-pos.x, pos.y, 0.0f);
rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
}
}
}
}
您通过使用将键盘输入存储在运动变量中
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
因此,当您尝试使用手机进行测试时,键盘输入为 0,因此没有移动
使用movement = touch.position
将触摸输入存储在更新 function
例如:
if (touch.phase == TouchPhase.Moved)
{
Vector2 pos = touch.position;
pos.x = (pos.x - width) / width;
pos.y = (pos.y - height) / height;
position = new Vector3(-pos.x, pos.y, 0.0f);
// Position the cube.
transform.position = position;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.