![](/img/trans.png)
[英]How can I make 2d object constantly moving in one direction, but when given horizontal input change direction but not change speed?
[英]How to make a game object move to the opposite direction of a constantly moving object? Unity 2D
我想要实现的是当我按下空格键时让圆圈向正方形的相反方向移动,正方形将模拟螺旋桨,例如:
这是我拥有的代码,它有点工作:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] GameObject rotatingPropellant;
[SerializeField] float rotationSpeed;
[SerializeField] float impulseForce;
Rigidbody2D playerRb;
void Start()
{
playerRb = GetComponent<Rigidbody2D>();
}
void Update()
{
RotatePropellant();
Move();
}
void RotatePropellant()
{
rotatingPropellant.transform.RotateAround(transform.position, new Vector3(0f, 0f, 1f), rotationSpeed * Time.deltaTime);
}
void Move()
{
if (Input.GetButtonDown("Jump"))
{
playerRb.velocity = -rotatingPropellant.transform.position * impulseForce * Time.deltaTime;
}
}
}
但有时即使正方形向上,圆圈也会向上移动(意味着应该向下推圆圈),不确定标志是否不正确或者我是否应该用不同的方法来解决这个问题
要获得运动方向,您可以使用此向量公式AB = B - A
。 该公式将为您提供与 B 空间相关的 A 的 position 向量,如果您对该向量进行归一化,您将获得运动方向
A 是球体,B 是正方形。 检查向量加法和减法。
所以这:
playerRb.velocity = -rotatingPropellant.transform.position * impulseForce * Time.deltaTime;
依赖于相对于世界零 position ( Vector3.zero
) 的rotatingPropellant
推进剂 position,这可能仅在推进剂围绕该零点旋转时才起作用。 您可能应该做的是获得差异:
Vector3 dir = (rotatingPropellant.transform.position - transform.position).normalized;
playerRb.velocity = dir * impulseForce * Time.deltaTime;
此外,您可以添加力而不是改变速度:
Vector3 dir = (rotatingPropellant.transform.position - transform.position).normalized;
playerRb.AddForce(dir * impulseForce, ForceMode2D.Impulse);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.