【问题标题】:Transforming a vector to adhere to a complimentary vector with ThreeJS使用 ThreeJS 转换向量以遵循互补向量
【发布时间】:2020-08-09 23:39:49
【问题描述】:

我在尝试用 threeJS 创建游戏引擎时遇到了一个麻烦的问题。 这是一道数学题,也是一道编程题。

我已经为玩家的化身实现了一个基于速​​度的移动系统 - 在这个例子中我使用了一辆坦克。

目前,当玩家撞到墙时,无论角度如何,坦克总是会死机。

但是,我希望坦克的速度发生变化,已强制跟随墙壁的角度,并且还减少了与该角度相关的幅度。

例如,在图 A 中,坦克在撞到墙壁后会继续尝试向前移动,但它的速度会发生变化,现在它会以降低的速度向前和侧向移动。

在图 B 中,坦克完全撞到墙上,其总速度达到 0。

在图 C 中,坦克从墙壁上掠过,它的整体速度只降低了一小部分。

我已经意识到我需要以某种方式将 Tank 的速度矢量与墙壁的法线矢量相结合,以生成调整后的矢量,但我正在努力以数学/编程方式表示这一点。

我尝试过使用:tank.velocity.multiply(wallFaceNormal);(tank.velocity 和 wallFaceNormal 都是 Vector3 对象。)但这似乎只在墙的角度为 0、90、180 或270.

【问题讨论】:

    标签: math three.js game-engine game-physics


    【解决方案1】:

    由于坦克不会跳跃或飞行,您应该只使用 2D 系统进行计算吗?

    我找到了一个链接,描述了汽车撞击实心砖墙的物理原理。

    http://colgatephys111.blogspot.com/2017/12/guardrail-lessens-force-of-impact.html

    希望对你有所帮助!

    编辑: 所以,出于好奇,我通过电话向一位理论物理学家询问了您的问题。

    您有 2 个单独的问题需要解决: 1. P1 撞墙时的速度 v' 是多少? 2. P2 车辆的新角度是多少?

    P2 应该相当容易,考虑到您的坦克正在调整墙壁的角度,您只需要计算墙壁“指向”的方向即可。

    P1 在物理学中,我们将讨论减小的力而不是速度,但是给定力 F1 的恒定限制(例如您的引擎)导致恒定的最大速度, 并且在给定的力下,墙壁对车辆 F2 的影响

    v = F1
    v' = F1'
    F1' = F1 - F2
    

    我认为 https://www.thoughtco.com/what-is-the-physics-of-a-car-collision-2698920 解释该怎么做

    【讨论】:

    • 感谢您的回复! (并为延迟道歉)奇怪的是,我也在和我的一个物理学家朋友谈论这件事!他向我发送了一些示例 C# 代码作为指导,但由于其中存在一些小错误以及我缺乏数学理解,我始终无法使其正常工作。我已将其作为潜在答案附加到问题中。
    【解决方案2】:

    物理学家提供的一些代码,当我将其转换为 Javascript 并将其应用于程序时,部分代码起作用了:

    Vector3 wallNormal = new Vector3(-0.5, 0.0, 0.5);
    Vector3 incomingVelocity = new Vector3(0.0, 0.0, -1.0);
    
    double magnitudeProduct = wallNormal.Length() * incomingVelocity.Length();
    double angleBetweenVelocityAndWall = ((-incomingVelocity).Dot(wallNormal)) / (magnitudeProduct);
    
    double newVelocityMagnitude = incomingVelocity.Length() * Math.Sin(angleBetweenVelocityAndWall);
    
    Vector3 upVector =incomingVelocity.Cross(wallNormal);
    Vector3 newDirection = wallNormal.Cross(upVector);
    Vector3 newVelocity = newDirection.Normalise() * newVelocityMagnitude;
    

    【讨论】:

      【解决方案3】:

      我在这个问题上做了一些工作,并制作了一个包含环境碰撞和运动衰减实用程序的迷你游戏“框架”。

      我写了一篇文章来解释它是如何工作的,可以在这里找到。 http://www.socket-two.com/main/resource/hdoc-tutorial

      但为了线程的完整性,这里对描述可用于在 ThreeJS 模拟中衰减运动的方法之一的部分进行了改编:

      ...

      至关重要的是,我的兴趣不是创建涉及大量物理的游戏,而只是创建以下游戏:

      • 玩家不能穿墙
      • 玩家不能从地板上掉下来

      我曾多次尝试实现一个可以实现这种行为的系统,但没有一个能真正令人满意地工作。到现在为止。

      就 ECS 如何融入应用架构而言,它是一个实用程序类。这是它的 API 形状:

      class Planeclamp {
          constructor({ floors /*Mesh[]*/, walls /*Mesh[]*/ })
          getSafePosition(startingPositionIn /*Vector3*/, intendedPositionIn /*Vector3*/) // Returns safePosition, which is a Vector3
      }
      

      如您所见,它的类在其构造函数中接受两个网格数组:应视为地板的网格和应视为墙壁的网格。现在当然在现实中,陡峭的地面和浅角的墙壁之间并没有明显的区别,但是为了模拟的目的,这种区别具有非常合理的完整性,并且会大大简化环境碰撞系统的逻辑。

      一旦构建了 Planeclamp 类的实例,就可以调用它的 getSafePosition 方法,将起始位置和预期位置转换为衰减位置。作为有眼光的读者,您会推断出衰减位置是预期位置,如果实用程序检测到任何碰撞,则会进行一些更改。

      这是如何在游戏循环中使用它,以确保玩家不会穿过墙壁或地板:

      const planeclamp = new Planeclamp({
          floors: [someFloorMesh, someOtherMesh],
          walls: [houseMesh, perimeterMesh, truckMesh],
      });
      
      const player = new Player();
      console.log(player.cage); // Object3D
      
      let playerPreviousPosition = player.cage.position; // Vector3
      
      function gameLoop(delta) {
          const playerIntendedPosition = new Three.Vector3(
              playerPreviousPosition.x,
              playerPreviousPosition.y + (10 * delta), // i.e. Gravity
              playerPreviousPosition.z + (1 * delta), // i.e. Walking forwards
          );
          let {
              safePosition, // Vector3
              grounded, // Boolean
              groundMaterial, // String
          } = planeclamp.getSafePosition(playerPreviousPosition, playerIntendedPosition);
          player.cage.position.copy(safePosition);
          playerPreviousPosition = player.cage.position; // Vector3
      }
      

      就是这样!如果您想使用此实用程序,可以在存储库中找到它。但如果您想了解更多关于其工作原理的信息,请继续阅读。

      Planeclamp.getSafePosition 方法分两个阶段计算出安全位置。首先,它使用垂直光线投射器查看播放器下方的内容,然后查看它是否应该阻止播放器进一步向下移动。其次,它使用水平光线投射器来查看是否应该阻止玩家水平移动。让我们先看一下垂直约束过程——这是两个步骤中更简单的一个。

      // Before we do anything, create a variable called "gated".
      // This will contain the safe new position that we will return at the end of
      // the function. When creating it, we let it default to the
      // intended position. If collisions are detected throughout the lifecycle
      // of this function, these values will be overwritten.
      let gated = {
          x: intendedPosition.x,
          y: intendedPosition.y,
          z: intendedPosition.z,
      };
      
      // Define the point in 3D space where we will shoot a ray from.
      // For those who haven't used raycasters before, a ray is just a line with a direction.
      // We use the player's intended position as the origin of the ray, but we
      // augment this by moving the origin up a little bit (backStepVert) to prevent tunneling.
      const start = intendedPosition.clone().sub(new Three.Vector3(
          0,
          (backStepVert * -1) - (heightOffset / 2),
          0)
      );
      
      // Now, define the direction of the ray, in the form of a vector.
      // By giving the vector X and Z values of 0, and a Y value of -1,
      // the ray shoots directly downwards.
      const direction = new Three.Vector3(0, -1, 0).normalize();
      
      // We now set the origin and direction of a raycaster that we instantiated
      // in the class constructor method.
      this.raycasters.vert.set(start, direction);
      
      // Now, we use the `intersectObjects` method of the ray.
      // This will return to us an array, filled with information about each
      // thing that the ray collided with.
      const dirCollisions = this.raycasters.vert.intersectObjects(this.floors, false);
      
      // Initialise a distanceToGround, a grounded variable, and a groundMaterial variable.
      let distanceToGround = null;
      let grounded = false;
      let groundMaterial = null;
      
      // If the dirCollisions array has at least one item in it, the
      // ray passed through one of our floor meshes.
      if (dirCollisions.length) {
      
          // ThreeJS returns the nearest intersection first in the collision
          // results array. As we are only interested in the nearest collision,
          // we pluck it out, and ignore the rest.
          const collision = dirCollisions[0];
      
          // Now, we work out the distance between where the players feet
          // would be if the players intended position became the players
          // actual position, and the collided object.
          distanceToGround = collision.distance - backStepVert - heightOffset;
      
          // If the distance is less than 0, then the player will pass through
          // the groud if their intended position is allowed to become
          // their actual position.
          if (distanceToGround < 0) {
      
              // We dont want that to hapen, so lets set the safe gated.y coordinate
              // to the y coordinate of the point in space at which the collision
              // happened. In other words, exactly where the ground is.
              gated.y = intendedPosition.y - distanceToGround;
      
              // Make a note that the player is now grounded.
              // We return this at the end of the function, along with
              // the safe position.
              grounded = true;
      
              // If the collided object also has a groundMaterial set inside
              // its userData (the place that threeJS lets us attach arbitrary
              // info to our objects), also set the groundMaterial. This is
              // also returned at the end of the function alongside the grounded
              // variable.
              if (collision.object.userData.groundMaterial) {
                  groundMaterial = collision.object.userData.groundMaterial;
              }
          }
      }
      

      这就是垂直环境限制。简单!

      横向环境约束系统稍微复杂一些。但本质上,它所做的是:

      1. 计算出玩家行进的水平方向。在旧世界的术语中,这可以被认为是北、南、东南、南西南等,但在 ThreeJS 中它由向量表示。
      2. 向玩家前进的方向投射光线。
      3. 使用射线确定允许玩家的预期位置是否会导致玩家穿过任何墙壁网格。

      正是在这一点上,水平 ECS 变得比垂直 ECS 更复杂。使用垂直 ECS,如果发生碰撞,我们只需将玩家 Y 位置设置为碰撞发生点的 Y 位置 - 有效地阻止玩家 Y 移动。但是,如果我们这样做是为了水平移动,这将导致非常令人沮丧的游戏体验。

      如果玩家一头撞到墙上,并在他们的轨道上停下来,这很好。但是如果玩家以一个非常浅的角度进入墙壁,只是擦过它,就会看起来他们已经“卡在”墙上了,并且会发现自己不得不转身离开它,并且注意不要碰到它再来一次。

      我们真正想要发生的是让玩家的水平速度衰减,以便他们沿着墙壁移动。因此,横向ECS如下进行:

      1. 获取被碰撞表面的法线。 (就我们的目的而言,法线可以描述为墙所面对的方向)
      2. 检查墙壁法线方向和玩家移动方向之间的差异。
      3. 使用差值计算出安全位置,即发生碰撞的空间点,增量为水平垂直于墙壁法线的向量,乘以玩家输入方向和墙壁的叉积正常。

      ...

      这是最终的实用程序类,完整的:

      import * as Three from '../../../vendor/three/three.module.js';
      
      class Planeclamp {
      
          constructor({
              scene,
              floors = [],
              walls = [],
              drawRays = true,
          } = {}) {
              this.drawRays = drawRays;
              this.floors = [];
              this.walls = [];
              this.scene = scene;
              this.objects = [];
      
              // Init collidable mesh lists
              this.addFloors(floors);
              this.addWalls(walls);
      
              // Create rays
              this.raycasters = {
                  vert: new Three.Raycaster(),
                  horzLeft: new Three.Raycaster(),
                  horzRight: new Three.Raycaster(),
                  correction: new Three.Raycaster(),
              };
          }
      
          setDrawRays(draw) {
              this.drawRays = draw;
          }
      
          addFloor(floor) {
              this.floors.push(floor);
          }
      
          removeFloor(floor) {
              this.floors = this.floors.filter(thisFloor => thisFloor !== floor);
          }
      
          addFloors(floors) {
              floors.forEach(floor => this.addFloor(floor));
          }
      
          resetFloors() {
              this.floors = [];
          }
      
          addWall(wall) {
              this.walls.push(wall);
          }
      
          removeWall(wall) {
              this.walls = this.walls.filter(thisWall => thisWall !== wall);
          }
      
          addWalls(walls) {
              walls.forEach(wall => this.addWall(wall));
          }
      
          resetWalls() {
              this.walls = [];
          }
      
          getSafePosition(startingPositionIn, intendedPositionIn, {
              collisionPadding = .5,
              heightOffset = 0,
          } = {}) {
      
              // ------------------ Setup -------------------
      
              // Parse args
              const startingPosition = startingPositionIn.clone();
              const intendedPosition = intendedPositionIn.clone();
              let grounded = false;
              let groundMaterial = null;
      
              // Augmenters
              const backStepVert = 50;
              const backStepHorz = 5;
              const backStepCorrection = 5;
      
              // Prepare output
              let gated = {
                  x: intendedPosition.x,
                  y: intendedPosition.y,
                  z: intendedPosition.z,
              };
      
              // Clean up previous debug visuals
              this.objects.map(object => this.scene.remove(object));
              this.objects = [];
      
              // ------------------ Vertical position gating -------------------
      
              // Adjust vertical position in gated.y.
              // Store grounded status in grounded.
              const start = intendedPosition.clone().sub(new Three.Vector3(
                  0,
                  (backStepVert * -1) - (heightOffset / 2),
                  0)
              );
              const direction = new Three.Vector3(0, -1, 0).normalize();
              this.raycasters.vert.set(start, direction);
              const dirCollisions = this.raycasters.vert.intersectObjects(this.floors, false);
              if (this.drawRays) {
                  const arrowColour = dirCollisions.length ? 0xff0000 : 0x0000ff;
                  const arrow = new Three.ArrowHelper(this.raycasters.vert.ray.direction, this.raycasters.vert.ray.origin, 300, arrowColour);
                  this.objects.push(arrow);
              }
              let distanceToGround = null;
              if (dirCollisions.length) {
                  const collision = dirCollisions[0];
                  distanceToGround = collision.distance - backStepVert - heightOffset;
                  if (distanceToGround < 0) {
                      gated.y = intendedPosition.y - distanceToGround;
                      grounded = true;
                      if (collision.object.userData.groundMaterial) {
                          groundMaterial = collision.object.userData.groundMaterial;
                      }
                  }
              }
      
              // ------------------ Horizontal position gating -------------------
      
              const horizontalOutputPosition = (() => {
      
                  // Init output position
                  const outputPosition = new Three.Vector3(intendedPosition.x, 0, intendedPosition.z);
      
                  // Store normalised input vector
                  const startingPos = startingPosition.clone();
                  const intendedPos = intendedPosition.clone();
                  startingPos.y = startingPositionIn.y + .5;
                  intendedPos.y = startingPositionIn.y + .5;
                  let inputVector = intendedPos.clone().sub(startingPos).normalize();
      
                  // Work out distances
                  const startingIntendedDist = startingPos.distanceTo(intendedPos);
                  const inputSpeed = startingIntendedDist;
      
                  // Define function for moving ray left and right
                  function adj(position, offset) {
                      const rayAdjuster = inputVector
                          .clone()
                          .applyAxisAngle(new Three.Vector3(0, 1, 0), Math.PI / 2)
                          .multiplyScalar(.5)
                          .multiplyScalar(offset);
                      return position.clone().add(rayAdjuster);
                  }
      
                  // Work out intersections and collision
                  let collisions = {
                      left: {
                          collision: null
                      },
                      right: {
                          collision: null
                      }
                  };
                  Object.keys(collisions).forEach(side => {
                      const rayOffset = side === 'left' ? -1 : 1;
      
                      const rayStart = adj(startingPos.clone().sub(inputVector.clone().multiplyScalar(2)), rayOffset);
                      const startingPosSide = adj(startingPos, rayOffset);
                      const intendedPosSide = adj(intendedPos, rayOffset);
                      const startingIntendedDistSide = startingPosSide.distanceTo(intendedPosSide);
      
                      const rayKey = 'horz' + _.startCase(side);
                      this.raycasters[rayKey].set(rayStart, inputVector);
                      const intersections = this.raycasters[rayKey].intersectObjects(this.walls, true);
                      for (let i = 0; i < intersections.length; i++) {
                          if (collisions[side].collision) break;
                          const thisIntersection = intersections[i];
                          const startingCollisionDist = startingPosSide.distanceTo(thisIntersection.point);
                          if (startingCollisionDist - collisionPadding <= startingIntendedDistSide) {
                              collisions[side].collision = thisIntersection;
                              collisions[side].offset = rayOffset;
                          }
                      }
      
                      if (inputSpeed && this.drawRays) {
                          this.objects.push(new Three.ArrowHelper(this.raycasters[rayKey].ray.direction, this.raycasters[rayKey].ray.origin, 300, 0x0000ff));
                      }
                  });
      
                  const [ leftCollision, rightCollision ] = [ collisions.left.collision, collisions.right.collision ];
                  const collisionData = (leftCollision?.distance || Infinity) < (rightCollision?.distance || Infinity) ? collisions.left : collisions.right;
      
                  if (collisionData.collision) {
      
                      // Var shorthands
                      const collision = collisionData.collision;
                      const normalVector = collision.face.normal.clone();
                      normalVector.transformDirection(collision.object.matrixWorld);
                      normalVector.normalize();
      
                      // Give output a baseline position that is the same as the collision position
                      let paddedCollision = collision.point.clone().sub(inputVector.clone().multiplyScalar(collisionPadding));
                      paddedCollision = adj(paddedCollision, collisionData.offset * -1);
                      outputPosition.x = paddedCollision.x;
                      outputPosition.z = paddedCollision.z;
      
                      if (leftCollision && rightCollision && leftCollision.face !== rightCollision.face) {
                          return startingPos;
                      }
      
                      // Work out difference between input vector and output / normal vector
                      const iCAngleCross = inputVector.clone().cross(normalVector).y; // -1 to 1
      
                      // Work out output vector
                      const outputVector = (() => {
                          const ivn = inputVector.clone().add(normalVector);
                          const xMultiplier = ivn.x > 0 ? 1 : -1;
                          const zMultiplier = ivn.z > 0 ? 1 : -1;
                          return new Three.Vector3(
                              Math.abs(normalVector.z) * xMultiplier,
                              0,
                              Math.abs(normalVector.x) * zMultiplier,
                          ).normalize();
                      })();
      
                      if (inputSpeed && this.drawRays) {
                          this.objects.push(new Three.ArrowHelper(normalVector, startingPos, 300, 0xff0000));
                      }
      
                      // Work out output speed
                      const outputSpeed = inputSpeed * Math.abs(iCAngleCross) * 0.8;
      
                      // Increment output position with output vector X output speed
                      outputPosition.add(outputVector.clone().multiplyScalar(outputSpeed));
      
                  }
      
                  // ------------------ Done -------------------
      
                  return outputPosition;
              })();
      
              gated.x = horizontalOutputPosition.x;
              gated.z = horizontalOutputPosition.z;
      
              // ------------------ Culmination -------------------
      
              // Add debug visuals
              this.objects.map(object => this.scene.add(object));
      
              // Return gated position
              const safePosition = new Three.Vector3(gated.x, gated.y, gated.z);
              return { safePosition, grounded, groundMaterial };
          }
      }
      
      export default Planeclamp;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多