Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何阻止我的两名球员同时移动?_C#_Unity3d - Fatal编程技术网

C# 如何阻止我的两名球员同时移动?

C# 如何阻止我的两名球员同时移动?,c#,unity3d,C#,Unity3d,//下面是我到目前为止的代码。无论我使用哪种控制方式,我的两个球都在同时移动。谁能帮我一把吗 public class PlayerController : MonoBehaviour { } 如何更改它,使我的两个播放器不会同时移动?对于Player1和Player2,您使用的是相同的转换代码。您正在以相同的速度替换这两个对象。 对于速度上的差异,让我们假设您想要以左箭头上的双倍速度更新播放器2,使用rb2.AddForce(Vector3.left*2*speed) 现在,如果你想让玩家只

//下面是我到目前为止的代码。无论我使用哪种控制方式,我的两个球都在同时移动。谁能帮我一把吗

public class PlayerController : MonoBehaviour
{

}


如何更改它,使我的两个播放器不会同时移动?

对于Player1和Player2,您使用的是相同的转换代码。您正在以相同的速度替换这两个对象。
对于速度上的差异,让我们假设您想要以左箭头上的双倍速度更新播放器2,使用
rb2.AddForce(Vector3.left*2*speed)

现在,如果你想让玩家只在某些事件上移动,甚至在
Update()
内将玩家的移动包含在鼠标按下或其他事件中。
你可以使用
RaycastHit
检查哪个游戏对象被点击,并只更新那个游戏对象。

你对两个角色都使用了相同的刚体。rb1和RB2是同一个刚体。你应该使用GameObject.Find或者类似的东西来让rb2成为第二个玩家的刚体


编辑:可以使用player2.GetComponent()抓住第二个玩家的刚体。假设此脚本附加到第一个播放器

有人能帮我吗?
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();
}