c# - 乒乓球游戏物理

标签 c# unity-game-engine game-physics pong

我正在学习教程,我理解了其中的大部分内容。我想问1件事。 这是我正在遵循的教程:

https://noobtuts.com/unity/2d-pong-game

这个方法被称为函数 HitFactor。

if (col.gameObject.name == "RacketLeft") {
        // Calculate hit Factor
        float y = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y);

        // Calculate direction, make length=1 via .normalized
        Vector2 dir = new Vector2(1, y).normalized;

        // Set Velocity with dir * speed
        GetComponent<Rigidbody2D>().velocity = dir * speed;
    }

Hit Factor方法是

   float hitFactor(Vector2 ballPos, Vector2 racketPos,
                    float racketHeight) {
        // ascii art:
        // ||  1 <- at the top of the racket
        // ||
        // ||  0 <- at the middle of the racket
        // ||
        // || -1 <- at the bottom of the racket
        return (ballPos.y - racketPos.y) / racketHeight;
    }

有人可以用例子向我解释一下吗?

(ballPos.y - racketPos.y) / racketHeight;

Image of ball and racket's y position

我真的无法理解,也不知道我应该读什么来让自己理解这一点。

最佳答案

教程中描述了游戏物理

Pong game physics

  • If the racket hits the ball at the top corner, then it should bounce off towards our top border.
  • If the racket hits the ball at the center, then it should bounce off towards the right, and not up or down at all.
  • If the racket hits the ball at the bottom corner, then it should bounce off towards our bottom border.

这意味着方向由 Racket 上的击球点决定。公式就是这样的

(ballPos.y - racketPos.y) / racketHeight

表示。如果ballPos.yracketPos.y相等,则 Racket 击中中心,球应垂直飞行(Y方向等于0)。如果击 Racket 在顶角,球应以 45° 角向上飞行(Y 为 1,参见 ASCII 艺术),如果 Racket 击在底部,球应以 45° 角向下飞行( Y 为 -1,请参见 ASCII 艺术)。 45° 角(向上或向下)是通过具有相同绝对值的速度的 X 和 Y 分量实现的。介于两者之间的任何值都会产生介于两者之间的值。

由于这种行为与 Racket 的尺寸无关,因此球到 Racket 中心的距离除以 Racket 的长度(实际上我认为应该是尺寸的一半,因为否则顶部为 0.5,底部为 -.5)。

关于c# - 乒乓球游戏物理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51979115/

相关文章:

c# - 如何禁用 ContextMenuStrip 中的菜单项?

unity-game-engine - Unity中看不到飞机

c - 简单递归帮助

python - 如何让两个角色在 PYGAME 中碰撞时不会相互碰撞?

javascript - 如何加速这个移动算法?在Javascript中

c# - 在 WPF 中绘制圆圈

c# - 通过 C# 显示 "Devices and Printers"窗口?

c# - 冲突的命名空间解析

variables - 使用 GetComponent 从另一个脚本访问变量

C# Unity onClick 事件中函数的参数错误