我有一个 2D 球,它有一个力并在不确定的方向上移动,我需要让球在用户触摸屏幕时相对于当前方向向右或向左圆形移动,而不改变速度。我该怎么做?
我试过这段代码,但是其他物理不能影响球,因为我们直接改变变换:
float angle = 0;
float radius = 1;
void FixedUpdate()
{
angle += speed * Time.deltaTime;
float x = center.x + Mathf.Cos(angle) * radius;
float y = center.y + Mathf.Sin(angle) * radius;
rigidbody.transform.position = new Vector3(x, y, 3);
}
就像物理学做的那样:
你的触摸位置有点像一个重力中心 → 使用相同的幅度连续分配一个新方向,但在一个新方向上,该方向与从中心到移动物体的矢量和旋转轴成 90° 角。
在代码中这可能看起来像
public class Example : MonoBehaviour
{
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Camera _camera;
[SerializeField] private Vector2 initialVelocity;
private bool doGravitation;
private Vector2 centerPos;
private void Awake()
{
if(!rb) rb = GetComponent<Rigidbody2D>();
if(!_camera) _camera = Camera.main;
rb.velocity = initialVelocity;
}
private void Update()
{
// check for touch support otherwise use mouse as fallback
// (for debugging on PC)
if (Input.touchSupported)
{
// not touching or too many -> do nothing
if (Input.touchCount != 1)
{
doGravitation = false;
return;
}
var touchPosition = Input.GetTouch(0).position;
centerPos = _camera.ScreenToWorldPoint(touchPosition);
doGravitation = true;
}
else
{
// mouse not pressed -> do nothing
if (!Input.GetMouseButton(0))
{
doGravitation = false;
return;
}
centerPos = _camera.ScreenToWorldPoint(Input.mousePosition);
doGravitation = true;
}
}
private void FixedUpdate()
{
if(!doGravitation) return;
// get current magnitude
var magnitude = rb.velocity.magnitude;
// get vector center <- obj
var gravityVector = centerPos - rb.position;
// check whether left or right of target
var left = Vector2.SignedAngle(rb.velocity, gravityVector) > 0;
// get new vector which is 90° on gravityDirection
// and world Z (since 2D game)
// normalize so it has magnitude = 1
var newDirection = Vector3.Cross(gravityVector, Vector3.forward).normalized;
// invert the newDirection in case user is touching right of movement direction
if (!left) newDirection *= -1;
// set new direction but keep speed(previously stored magnitude)
rb.velocity = newDirection * magnitude;
}
}
另见:
请注意,这有时看起来很奇怪,尤其是在球前面接触时,因为我们将其强制到可能与当前运动具有奇怪角度的圆形曲线上。你可以解决这个问题,但这取决于你;)
我是一名优秀的程序员,十分优秀!