我有一个 Hookshot 类,它包含一个公共协程,当它附加到的对象(hookshot)在另一个脚本中实例化时,我正在调用它。目标是协程 CastHookshot 将对象移出设定的距离,然后启动 ReturnHookshot 协程将其移回玩家。平稳的前后运动。将会有额外的设计选择禁止我为此使用 Mathf.PingPong 或 Mathf.Sin,因此它需要是两个协程。无论如何,由于某种原因,物体根本没有移动,我不知道为什么。我用 Debug.Log 进行了测试,知道协程正在被击中。传入的 castDistance 是 50,因此循环的距离条件也不应该成为问题。
public class Hookshot : MonoBehaviour
{
private Vector2 playerPos;
private readonly float hookshotCastTime = 0.2f;
private readonly float hookshotReturnSpeed = 4f;
private readonly float hookshotDistanceBuffer = 0.2f;
public IEnumerator CastHookshot(float castDistance, Vector2 aimDir)
{
playerPos = gameObject.transform.position;
Vector2 target = playerPos + (castDistance * aimDir);
float speed = castDistance / hookshotCastTime * Time.deltaTime;
while (Vector2.Distance(transform.position, target) > hookshotDistanceBuffer)
{
transform.position = Vector2.MoveTowards(playerPos, target, speed);
yield …Run Code Online (Sandbox Code Playgroud) 我正在使用以下代码尝试在屏幕顶部为球创建CGPoint:
func randomBallPosition() -> CGPoint {
let random = CGFloat((arc4random_uniform(8) + 1) / 10)
let randomX = CGFloat(self.frame.size.width * random)
let staticY = CGFloat(self.frame.size.height * 0.95)
return CGPoint(x: randomX, y: staticY)
}
Run Code Online (Sandbox Code Playgroud)
然而,球始终位于(0,y),我不确定为什么.