Skip to main content
 首页 » 编程设计

c#之使用首选键统一移动玩家

2024年02月05日11JustinYoung

我正在尝试通过添加两个球以不同的方式完成滚球教程 ( https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial )。 所以两个玩家可以玩游戏。 但我面临的问题是我想为第二个玩家配置首选键,就像第一个玩家使用传统的箭头键,第二个玩家使用 w、a、s、d 从左到右移动......我的第一个玩家的 c-sharp 代码是这样的...

using UnityEngine; 
using System.Collections; 
 
public class PlayerController : MonoBehaviour { 
 
public float speed; 
 
private Rigidbody rb; 
void Start() 
{ 
    rb = GetComponent<Rigidbody> (); 
} 
 
void FixedUpdate() 
{ 
    float moveHorizontal = Input.GetAxis("Horizontal"); 
    float moveVertical = Input.GetAxis("Vertical"); 
 
    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);                //Values for movement vector 3 takes three arguments like x y z for positions. 
 
    rb.AddForce (movement * speed); 
} 
} 

如果有人有解决办法请告诉我

请您参考如下方法:

已回答类似问题 here .

要求您不修改关键控件的最简单解决方案是根本不使用 Input.GetAxis。使用 Input.GetKey() 及其 keycodes 枚举检测每个按键。问题解决了!现在从编辑器中分配两个球。如果需要,您可以轻松修改它以使用一个球。

using UnityEngine; 
using System.Collections; 
 
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 Rigidbody player1RB; //Player 1 Rigidbody 
    public Rigidbody player2RB; //Player 2 Rigidbody 
 
 
    //Player 1 Code with aswd keys 
    void Player1Movement() 
    { 
        if (Input.GetKey(KeyCode.A)) 
        { 
            player1RB.AddForce(Vector3.left * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.D)) 
        { 
            player1RB.AddForce(Vector3.right * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.W)) 
        { 
            player1RB.AddForce(Vector3.forward * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.S)) 
        { 
            player1RB.AddForce(Vector3.back * speed); 
 
        } 
    } 
 
    //Player 2 Code with arrow keys 
    void Player2Movement() 
    { 
        if (Input.GetKey(KeyCode.LeftArrow)) 
        { 
            player2RB.AddForce(Vector3.left * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.RightArrow)) 
        { 
            player2RB.AddForce(Vector3.right * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.UpArrow)) 
        { 
            player2RB.AddForce(Vector3.forward * speed); 
 
        } 
 
        if (Input.GetKey(KeyCode.DownArrow)) 
        { 
            player2RB.AddForce(Vector3.back * speed); 
 
        } 
    } 
 
    // Update is called once per frame 
    void FixedUpdate() 
    { 
        Player1Movement(); 
        Player2Movement(); 
    } 
}