角色的控制和键盘输入,这一章将学习通过键盘输入来控制游戏中的角色,游戏对象。
1.在update方法中修改方法如下:
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
Debug.Log(horizontal);
Vector2 position = transform.position;
position.x = position.x + 0.1f * horizontal;
transform.position = position;
}
第一行:float horizontal = Input.GetAxis("Horizontal");表示获得当前的水平值。
第二行:position.x = position.x + 0.1f * horizontal;
;表示如果你按左键,则向左移动0.1个位置,按右键,则向右移动0.1个位置。
2.运行时,可以在控制台上看到结果。
3.同理,也可以增加上下的功能,代码如下:
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.x = position.x + 0.1f * horizontal;
position.y = position.y + 0.1f * vertical;
transform.position = position;
}
运行时,按上下左右键盘,测试下效果。
4.定时和帧数
一般地,Unity每秒渲染60帧以上。
void Start()
{
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 10;
}
在start方法中,增加以上的语句。则目标是每秒渲染10帧。
f your game runs at 60 frames per second, Ruby will move at 0.1 * 60, so six units per second. But if the game runs at ten frames per second, like you just forced it to do, Ruby only moves 0.1 * 10, so 1 unit per second! If a player has a very old computer that can only run the game at 30 frames per second and another player has a computer that can run it at 120 frames per second, those two players will have a main character that moves at radically different speeds. This will make the game either harder or easier to play, depending on the machine running the game.
5.不同电脑同步的问题
public class RubyController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//QualitySettings.vSyncCount = 0;
//Application.targetFrameRate = 10;
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.x = position.x + 0.1f * horizontal * Time.deltaTime;
position.y = position.y + 0.1f * vertical * Time.deltaTime;
transform.position = position;
}
}
deltaTime, contained inside Time, is a variable that Unity fills with the time it takes for a frame to be rendered.
包含在时间内的deltaTime是一个变量,Unity用渲染帧所需的时间填充它。
上一句是英语的原话,对deltaTime的解释。感觉是通过deltaTime来控制不同电脑的渲染帧所需的时间的同步问题。
6.检查脚本,测试效果
public class RubyController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.x = position.x + 3.0f * horizontal * Time.deltaTime;
position.y = position.y + 3.0f * vertical * Time.deltaTime;
transform.position = position;
}
}