【Unity】マウスの動きにカメラが追従してオブジェクトを中心に回転し、視線の方向に合わせてオブジェクトが動きます。

説明する

マウスの動きに応じてカメラがオブジェクトに追従して回転することを認識し、カメラの前にあるオブジェクトを中心として、カメラはオブジェクトの周囲を回転し、常にカメラがオブジェクトを向くようにします。

効果を実感

ここに画像の説明を挿入します

Unityコンポーネントの設定

カメラコンポーネントの設定

ここに画像の説明を挿入します

ボディコンポーネントの設定

ここに画像の説明を挿入します

コードを実装する

CameraRotateMove.cs カメラのフォローと回転

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMoveRotate : MonoBehaviour
{
    
    
    public float LerpPar;
    public Transform FollowTrans;
    public Vector3 Offset;
    public Transform CameraTransform1;
    Vector3 ForwardDirec;

    // Start is called before the first frame update
    void Start()
    {
    
    
        Offset = transform.position - FollowTrans.position;
    }

    // Update is called once per frame
    void Update()
    {
    
    
        float dx = Input.GetAxis("Mouse X");

        Offset = Quaternion.AngleAxis(dx * 10, Vector3.up) * Offset;
        transform.position = Vector3.Lerp(transform.position, (FollowTrans.position + Offset), LerpPar * Time.deltaTime);
        transform.rotation = Quaternion.LookRotation(-1 * Offset);


    }
}

move_better.cs キーに応じてオブジェクトが移動します

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move_better : MonoBehaviour
{
    
    
    public float speed = 3.0f;
    private Rigidbody mRigidbody;
    public Transform FollowTrans;
    public Vector3 Offset;
    public Transform CameraTrans;
    float Offset_x, Offset_z;
    // Start is called before the first frame update
    void Start()
    {
    
    
        mRigidbody = GetComponent<Rigidbody>();
        Offset = FollowTrans.position - CameraTrans.position;

    }

    // Update is called once per frame
    void Update()
    {
    
    
        Offset = FollowTrans.position - CameraTrans.position;
        Vector3 direction_forward = new Vector3(0, 0, Offset_z);
        Vector3 direction_left = new Vector3(Offset_x, 0, 0);


        if (Input.GetKeyDown("w"))
        {
    
    
            mRigidbody.velocity = CameraTrans.forward * speed;
        }

        if (Input.GetKeyDown("s"))
        {
    
    
            mRigidbody.velocity = -1 * CameraTrans.forward * speed;
        }
        if (Input.GetKeyDown("a"))
        {
    
    
            mRigidbody.velocity = -1 * CameraTrans.right * speed;
        }
        if (Input.GetKeyDown("d"))
        {
    
    
            mRigidbody.velocity = CameraTrans.right * speed;
        }
        if (Input.GetKeyDown("space"))
        {
    
    
            mRigidbody.velocity = 2 * Vector3.up * speed;
        }
    }
}

おすすめ

転載: blog.csdn.net/m0_50939789/article/details/128365674