//这是我到目前为止的代码。无论我使用哪种控件,我的两个球都在同一时间移动。有人可以请帮忙吗?
public class PlayerController : MonoBehaviour
{
public float speed = 80.0f; // Code for how fast the ball can move. Also it will be public so we can change it inside of Unity itself.
public GameObject player1; //Player 1 Rigidbody
public GameObject player2; //Player 2 Rigidbody
private Rigidbody rb;
private Rigidbody rb2;
void Start ()
{
rb = GetComponent<Rigidbody> ();
rb2 = GetComponent<Rigidbody> ();
player1 = GameObject.Find("Player");
player2 = GameObject.Find("Player 2");
}
//Player 1 Code with aswd keys
void Player1Movement()
{
if (player1 = GameObject.Find("Player"))
{
if (Input.GetKey (KeyCode.A)) {
rb.AddForce (Vector3.left * speed);
}
if (Input.GetKey (KeyCode.D)) {
rb.AddForce (Vector3.right * speed);
}
if (Input.GetKey (KeyCode.W)) {
rb.AddForce (Vector3.forward * speed);
}
if (Input.GetKey (KeyCode.S)) {
rb.AddForce (Vector3.back * speed);
}
}
}
//Player 2 Code with arrow keys
void Player2Movement()
{
if( player2 = GameObject.Find("Player 2"))
{
if (Input.GetKey(KeyCode.LeftArrow))
{
rb2.AddForce(Vector3.left * speed);
}
if (Input.GetKey(KeyCode.RightArrow))
{
rb2.AddForce(Vector3.right * speed);
}
if (Input.GetKey(KeyCode.UpArrow))
{
rb2.AddForce(Vector3.forward * speed);
}
if (Input.GetKey(KeyCode.DownArrow))
{
rb2.AddForce(Vector3.back * speed);
}
}
}
// Update is called once per frame
void Update()
{
Player1Movement();
Player2Movement();
}
}
我如何更改它以便我的两位玩家不会同时移动?
答案 0 :(得分:1)
你以某种方式对两个角色使用相同的刚体。 rb1和2是相同的刚体。你应该使用GameObject.Find或类似的东西让rb2成为第二个玩家的刚体。
编辑:您可以使用player2.GetComponent()来抓住第二个玩家的刚体。假设此脚本附加到第一个播放器
答案 1 :(得分:0)
对于Player1和Player2,您使用相同的转换代码。你以相同的速度取代两者
对于速度差异,假设您想要在左箭头上以双倍速度更新玩家2,请使用rb2.AddForce(Vector3.left *2* speed);
现在,如果您希望玩家仅在某些内容上移动,那么在Update()
内将您的玩家动作包含在鼠标按下或其他事件中。
您可以使用RaycastHit
来检查哪个GameObject被点击并更新只有一个。