You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何实现角色八方向移动且采用固定相机(非跟随式)?

Fixing 8-Directional Movement with Rigidbody for Fixed-Camera Unity (RE2 Classic Style)

Hey there! I know how frustrating it is to spend days stuck on a wonky movement script—let's get this sorted for you. Since you want that classic Resident Evil 2 fixed-camera feel with 8-directional movement and proper Rigidbody interactions, here's a step-by-step solution:

First, Get Your Setup Right (Critical for Rigidbody)

Before diving into code, fix these common setup issues that break physics interactions:

  • Character Object: Add a Rigidbody component to your player. In the inspector:
    • Check Freeze Rotation for X, Y, Z (stops the character from tilting/spinning randomly when moving)
    • Set Collision Detection to Continuous Dynamic (prevents weird collision glitches with walls/objects)
    • Toggle Use Gravity based on your scene (turn it off if you're making a fixed-camera game without jumping/falling)
    • Add a Capsule Collider (or matching collider) and resize it to fit your character model perfectly
  • Camera: Place your camera at the fixed position/rotation you want in the scene—no follow scripts needed, just leave it static and tag it as "MainCamera".

Working Rigidbody 8-Directional Movement Script

This script uses Unity's physics system properly (no messy direct transform edits) and handles movement relative to your fixed camera:

using UnityEngine;

public class FixedCamera8DirMovement : MonoBehaviour
{
    [Header("Movement Settings")]
    [SerializeField] private float moveSpeed = 5f;
    private Rigidbody rb;
    private Camera fixedCamera;

    void Awake()
    {
        // Grab components automatically (no need to drag in the inspector)
        rb = GetComponent<Rigidbody>();
        fixedCamera = Camera.main;
    }

    // Use FixedUpdate for ALL physics-related actions
    void FixedUpdate()
    {
        // Get raw input (gives clean -1, 0, 1 values for 8-directional control)
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");

        // Build our input direction vector
        Vector3 inputDir = new Vector3(horizontalInput, 0f, verticalInput);
        
        // Normalize to prevent faster diagonal movement (a common 8-direction bug)
        if (inputDir.magnitude > 1f)
        {
            inputDir.Normalize();
        }

        // Convert input to match the fixed camera's perspective
        // Lock movement to the XZ plane (no vertical movement)
        Vector3 cameraForward = fixedCamera.transform.forward;
        cameraForward.y = 0f;
        cameraForward.Normalize();

        Vector3 cameraRight = fixedCamera.transform.right;
        cameraRight.y = 0f;
        cameraRight.Normalize();

        Vector3 moveDir = (cameraForward * verticalInput) + (cameraRight * horizontalInput);

        // Move with Rigidbody (proper physics collision/interaction)
        rb.MovePosition(transform.position + moveDir * moveSpeed * Time.fixedDeltaTime);

        // Optional: Make character face the direction they're moving
        if (moveDir != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(moveDir);
        }
    }
}

Key Fixes & Why This Works

  • FixedUpdate Over Update: Physics operations (like moving Rigidbody) must run in FixedUpdate—this syncs with Unity's physics tick and eliminates jitter or broken collisions.
  • No Direct Transform Edits: Using rb.MovePosition lets the physics engine handle collisions, triggers, and interactions correctly (direct transform.position edits bypass physics, which was almost certainly causing your earlier issues).
  • Camera-Relative Movement: Converts your input to match the fixed camera's angle, so pressing "up" moves the character toward the top of the screen—just like classic RE2.
  • Normalized Input: Ensures diagonal movement isn't faster than straight-line movement.

Quick Troubleshooting

If you still have Rigidbody problems:

  • Double-check that your Rigidbody component is attached to the same object as this script (or assign it manually in the inspector if needed)
  • Make sure your character's collider isn't overlapping with scene geometry (this can make the Rigidbody get stuck or behave erratically)
  • Disable any other scripts that modify your character's transform or Rigidbody—conflicting scripts are a frequent culprit
  • If your character floats, enable Freeze Position Y in the Rigidbody constraints (great for flat-level fixed-camera games)

内容的提问来源于stack exchange,提问作者Gast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:18:10