[英]How to make a game object move to the opposite direction of a constantly moving object? Unity 2D
[英]How can I make 2d object constantly moving in one direction, but when given horizontal input change direction but not change speed?
我很抱歉,因为我是 Unity 库和 Unity 本身的纯菜鸟。
我正在创建一个简单的 2d 游戏,其中一个 2d 对象需要不断地朝着一个方向移动,但是当应用水平输入(例如 A、D)时,它需要改变运动矢量而不是改变速度。
该对象有一个属性 Rididbody2d
这是我到目前为止想到的:
{
[SerializeField]
private float speed;
[SerializeField]
private float rotationSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update ()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector2 movementDirection = new Vector2(horizontalInput, verticalInput);
float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude);
movementDirection.Normalize();
transform.Translate(movementDirection * speed * inputMagnitude * Time.deltaTime, Space.World);
if (movementDirection != Vector2.zero) {
Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, movementDirection);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
}
我的想法是,在更新期间,我们应该了解输入是否已注册,如果是,则当前向量乘以 (?) 已接收的角度(如果按下 0.1 秒 -> 0deg+1deg 如果按下2 秒 -> 0deg + 例如 90 度)。
然而! 按照教程,我设法让这个东西只有在按下键时才能移动。 我用谷歌搜索了一下,发现实际上没有任何帮助。 手册重读了很多次。 请帮我!
PS 英语不是我的母语,如有错误请见谅!
只要物理参与你不想做任何通过transform
可言,而是通过刚体部件,也没有Update
,但在FixedUpdate
..否则,你都挺奇怪的行为,并打破他的物理/冲突检测!
在我看来,您想要做的是:
[SerializeField] private float speed;
[SerializeField] private float rotationSpeed;
// reference this in the Inspector if possible
[SerializeField] private Rigidbody2D rigidbody;
// keep track of the target rotation
// for Rigidbody2D this is a simple float for the rotation angle
private float angle = 0;
private void Awake()
{
// as fallback get the Rigidboy2D on runtime
if(!rigidbody) rigidbody = GetComponent<Rigidbody2D>();
}
private void Update ()
{
// Still get user input in Update to not miss a frame
// evtl you would need to swap the sign according to your needs
angle += Time.deltaTime * rotationSpeed * Input.GetAxis("Horizontal");
}
private void FixedUpdate()
{
// rotate the Rigidbody applying the configured interpolation
rb.MoveRotation(angle);
// assuming if the object is not rotated you want to go right
// otherwise simply change this vector
rb.velocity = rb.GetRelativeVector(Vector3.right).normalized * speed;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.