如何在统一C#中围绕播放器旋转相机

时间:2019-05-30 16:52:30

标签: c# unity3d

我需要在按住鼠标左键的同时围绕我的玩家游戏对象旋转摄像机。我将如何处理?

此外,我对Vector 3有所了解,但我对它没有完全的了解。任何能够解释它的人将不胜感激。

我看过youtube视频,this one正是我想要的概念。我只是在将其应用于我的代码时遇到了麻烦。

我有点时间紧迫,考试快要结束了,我的老师并没有解释视频中解释的大多数内容。

///这是我在摄像机内跟随球/球员的代码

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

1 个答案:

答案 0 :(得分:0)

尝试一下。该脚本在您的相机上。

基本上,该脚本通过首先获取鼠标移动的方向来起作用。在这种情况下,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

相关问题