所以这是我的代码:(我是新的,我知道这是不正确的!)BTW这是为Unity
void Update () {
if (Input.GetButtonDown("Left"))
{
Transform.position xPrevPos yPrevPos
rb.velocity = new Vector2(horzMove, 0) * speed;
if(Transform.position == x + 5f)
{
## DO SOMETHING ##
}
}
}
所以我想要做的是首先检查左按钮是否被按下,然后记住当前位置,然后开始移动,然后如果它到达我希望它停止的位置并听取另一个按钮被按下。我写x + 5f的原因是因为我希望它在停止之前将该距离移动到左边
希望你明白!
答案 0 :(得分:2)
此脚本取自官方Unity网站上的其中一个教程。这是一艘太空船控制器。您在检查器中设置了一些边界,因此玩家无法将太空船移动到这些边界之外
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
//public variables you can modify from the inspector
public float speed;
public float tilt;
public Boundary boundary;
void FixedUpdate ()
{
//To read the inputs of the player. The Horizontal and Vertical axis
//Are defined in the Editor, Settings Manager, Input Manager.
//You can change that for your own inputs like:
//Input.GetKeyDown(KeyCode.Enter) or key you want to use
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
//Creates a VEctor3D with the inputs and applies the movement
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rigidbody.velocity = movement * speed;
//This part keeps the spaceship inside the boundary you passed as parameter
rigidbody.position = new Vector3
(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
);
//This part is just to make the spaceship tilt to one side or
//another to make it more realistic
rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
}
}
如果你是全新的,我建议你在开始发展自己的想法之前先开始观看所有或至少一些这些教程。它会让你更轻松。
https://unity3d.com/es/earn/tutorials/projects/space-shooter/moving-the-player?playlist=17147
教程:https://unity3d.com/es/learn/tutorials
修改:您的问题为什么他们在2D游戏中使用Vector3:
基本上即使您正在开发2D游戏,引擎也有3维空间,因此如果您定义了Vector2,它将被转换为Vector3(然后为第三维提供0值)。因此,在本教程中,他们定义了一个Vector3,它在y坐标中的值为0。