1. ホーム
  2. c#

[解決済み] Unity c#でプレイヤーの周りにカメラを回転させる方法

2022-02-26 14:44:01

質問

マウスの左ボタンを押しながら、プレイヤーのゲームオブジェクトの周囲でカメラを回転させる必要があります。どのようにアプローチすればよいのでしょうか?

また、ベクター3について少し読みましたが、完全に理解しているわけではありません。どなたか解説していただけると助かります。

youtubeの動画を見たり これ は、まさに私が求めていたコンセプトです。ただ、自分のコードに適用するのに苦労していました。

試験も近いし、先生もビデオで説明されているようなことはほとんど説明してくれないし、ちょっと時間がないんです。

// これは、ボール/プレイヤーを追うカメラ内の私のコードです。

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

public class ScriptBallCam : MonoBehaviour
{
public GameObject player;

private Vector3 offset;

void Start()
{
    offset = transform.position - player.transform.position;
}

void LateUpdate()
{
    transform.position = player.transform.position + offset;
}

//カメラ内のコード終了

//プレーヤー/ボールの内部コード

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

public class ScriptBall : MonoBehaviour
{



public float speed;



private Rigidbody rb;





void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}

// 終了コード

私が期待している結果は、まさに以下の1:22に示されています。

https://www.youtube.com/watch?v=xcn7hz7J7sI

解決方法は?

これを試してみてください。スクリプトはあなたのカメラに入ります。

基本的にこのスクリプトは、まずマウスの移動した方向を取得することで動作します。この場合、X軸は Mouse X (左右の方向)。次に、回転速度 turnSpeed を使用して、プレーヤーの周りをその角度だけ回転させます。 Quaternion.AngleAxis . 最後に、カメラが常にプレイヤーを見ていることを確認するため、次のようにします。 transform.LookAt

 using UnityEngine;  
 using System.Collections;    

public class OrbitPlayer : MonoBehaviour {

     public float turnSpeed = 5.0f;
     public GameObject player;

     private Transform playerTransform;     
     private Vector3 offset;
     private float yOffset = 10.0f;
     private float zOffset = 10.0f;

     void Start () {
         playerTransform = player.transform;
         offset = new Vector3(playerTransform.position.x, playerTransform.position.y + yOffset, playerTransform.position.z + zOffset);
     }

     void FixedUpdate()
     {
         offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
         transform.position = playerTransform.position + offset; 
         transform.LookAt(playerTransform.position);
     }  
}

このトピックについては、こちらで多くの情報が提供されています。 https://answers.unity.com/questions/600577/camera-rotation-around-player-while-following.html