使用首选键统一移动玩家 [英] Using preferred keys to move a player in unity
问题描述
我正在尝试完成滚球教程( https://unity3d. com/learn/tutorials/projects/roll-ball-tutorial )以不同的方式添加两个球. 因此,两个玩家可以玩游戏. 但是我面临的问题是我想为第二个播放器配置首选键,例如firsl播放器使用传统的箭头键,而第二个播放器使用w,a,s,d来左右左右移动...我的第一个玩家的C清晰代码是这样...
I am trying to complete roll a ball tutorial (https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) in a different way by adding two balls. So two players can play the game. But the problem i am facing is that i want to configure the preferred keys for the second player like the firsl player uses the traditional arrow keys and the second player use w,a,s,d to move up left down right... my c-sharp code for the first player is this...
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);
}
}
让我知道是否有人有解决办法
Let me know if anyone have solution
推荐答案
已回答类似的问题此处.
不需要您修改按键控件的最简单解决方案是完全不使用Input.GetAxis
.用Input.GetKey()
及其keycodes
枚举检测每个按键.问题解决了!现在从编辑器分配两个球.如果需要的话,您可以轻松地对其进行修改以与一个球一起使用.
The easiest solution that will require you not modify your key controls is to not use Input.GetAxis
at-all. Detect each key press with Input.GetKey()
and their keycodes
enum. Problem solved! Now assign the two balls from the Editor. You can easily modify it to work with one ball if that's what you want.
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();
}
}
这篇关于使用首选键统一移动玩家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!