Unity 玩家 3D 和 2D 墙跳跃教程
跳墙是平台游戏和动作游戏中普遍存在的一种机制,允许玩家跳下墙壁,增加了导航的复杂性和多功能性。本教程旨在将跳墙集成到提供的 FPS 控制器中。到最后,玩家角色将能够在 2D 和 3D 设置中执行墙跳。
使用 'SC_FPSController' 脚本实现 3D 墙跳
从 Unity FPS 控制器 教程中给定的基本代码开始,我们将介绍墙跳机制。
第 1 步:设置墙壁检测
- 在 Unity 中添加一个名为 "Wall" 的新图层,用于放置可以从墙上跳下来的对象。
- 使用以下变量更新 'SC_FPSController' 类(您可以从我们的 Unity FPS 控制器 教程获取该类):
public LayerMask wallLayer;
public float wallJumpForce = 10f;
private bool isTouchingWall = false;
第 2 步:检测墙壁
- 在 'Update()' 方法中合并以下逻辑来检测墙壁:
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.right, out hit, 1f, wallLayer) || Physics.Raycast(transform.position, -transform.right, out hit, 1f, wallLayer))
{
isTouchingWall = true;
}
else
{
isTouchingWall = false;
}
上面代码中的光线投射将检测玩家左侧和右侧的墙壁。
第 3 步:实现 3D 墙跳
- 在 'Update()' 方法中,在地面跳跃逻辑之后插入:
else if (Input.GetButton("Jump") && canMove && isTouchingWall)
{
moveDirection.y = wallJumpForce;
// This adds a bit of horizontal force opposite the wall for a more dynamic jump
if (Physics.Raycast(transform.position, transform.right, 1f, wallLayer))
{
moveDirection += -transform.right * wallJumpForce / 2.5f; // Adjust the divisor for stronger/weaker push.
}
else if (Physics.Raycast(transform.position, -transform.right, 1f, wallLayer))
{
moveDirection += transform.right * wallJumpForce / 2.5f;
}
}
上面代码中的逻辑检查玩家是否按下了跳跃按钮、是否可以移动以及是否正在接触墙壁。如果是这样,它会产生一个垂直力和一个远离墙壁的轻微水平力。
使用 'CharacterController2D' 脚本实现 2D 墙跳
从 2D 角色控制器 Unity 教程中给定的基本代码开始,我们将介绍 墙跳 机制。
第 1 步:设置墙壁检测
- 在 Unity 中添加一个名为 "Wall" 的新图层,用于放置可以从墙上跳下来的对象。
- 使用以下变量更新 'CharacterController2D' 类,您可以从我们的 2D 角色控制器 Unity 教程中获取该类:
public LayerMask wallLayer;
public float wallJumpForce = 10f;
private bool isTouchingWall = false;
步骤 2:以 2D 方式检测墙壁
- 在 'Update()' 方法中合并以下逻辑来检测墙壁:
RaycastHit2D wallHitLeft = Physics2D.Raycast(transform.position, Vector2.left, 1f, wallLayer);
RaycastHit2D wallHitRight = Physics2D.Raycast(transform.position, Vector2.right, 1f, wallLayer);
if (wallHitLeft.collider != null || wallHitRight.collider != null)
{
isTouchingWall = true;
}
else
{
isTouchingWall = false;
}
第 3 步:实现 2D 的墙跳
- 在 'Update()' 方法中,在地面跳跃逻辑之后插入:
if (Input.GetKeyDown(KeyCode.W) && isTouchingWall && !isGrounded)
{
r2d.velocity = new Vector2(r2d.velocity.x, jumpHeight);
if (wallHitLeft.collider != null)
{
r2d.AddForce(new Vector2(wallJumpForce, 0)); // Push to the right when wall is on the left
}
else if (wallHitRight.collider != null)
{
r2d.AddForce(new Vector2(-wallJumpForce, 0)); // Push to the left when wall is on the right
}
}
解决的问题:
- 角色如何在 Unity 中检测墙壁?:角色可以使用光线投射 检测墙壁。通过从玩家向所需方向发射不可见光线,人们可以确定某个物体(例如墙壁)是否与该光线相交。
- Unity 中 2D 和 3D 墙跳跃实现有什么区别?:在 Unity 中,2D 物理使用 'Physics2D' 方法(如 'Physics2D.Raycast()'),而 3D 物理则使用 'Physics' 方法(如 'Physics.Raycast()' )。逻辑仍然相对相似,但方法和方向(Vector2 用于 2D,Vector3 用于 3D)有所不同。
结论
此添加使 2D 空间中的角色能够从墙壁上跳下来。为了确保流畅的游戏体验,可能需要对力值进行实验。通过整合这些步骤,玩家会发现 2D 角色的运动在有墙壁的环境中更加灵活和动态。