Unity3D:相机不遵循播放器



我在游戏开发方面是相当新的,我有一个代码,可以根据玩家的运动使相机移动。玩家的动作脚本:

using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
//to store movement
Vector3 movement;
Rigidbody playerRigidbody;
int floorMask;
float camRayLenghth = 100f;
//gets called regardless if the script is enabled or not
void Awake(){
    floorMask = LayerMask.GetMask ("Floor");
    playerRigidbody = GetComponent<Rigidbody> ();
    //Input.ResetInputAxes ();
}
//unity calls automatically on every script and fire any physics object
void FixedUpdate(){
    float h = Input.GetAxisRaw ("Horizontal");
    float v = Input.GetAxisRaw ("Vertical");
    Move (h, v);
    //Rotate ();
    Turning ();
}
void Move(float h, float v){
    movement.Set (h,0f,v);
    movement = movement.normalized * speed * Time.deltaTime;
    playerRigidbody.MovePosition (transform.position + movement);
}
void Turning (){
    Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
    RaycastHit floorHit;
    if (Physics.Raycast (camRay,out floorHit,camRayLenghth,floorMask)) {
        Vector3 playerToMouse = floorHit.point - transform.position;
        playerToMouse.y = 0f;
        Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
        playerRigidbody.MoveRotation (newRotation);
    }
}
}

这是附加到主相机上的脚本:

using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
// a target for camera to follow
public Transform player;
// how fast the camera moves
public float smoothing = 4f;
//the initial offset from the target
Vector3 offset;
void start(){
    //calculation of initial offset (distance) between player and camera
    offset = transform.position - player.position;
    Debug.Log ("offset is " + offset);
}
void FixedUpdate (){
    //updates the position of the camera based on the player's position and offset
    Vector3 playerCameraPosition = player.position + offset;
    //make an smooth transfer of location of camera using lerp
    transform.position = Vector3.Lerp(transform.position, playerCameraPosition, smoothing * Time.deltaTime);            
}
}

但是,当我玩脚本时,即使玩家还没有移动,游戏摄像机也会开始重新安置并向地面移动。如果我从相机上删除脚本并将相机成为玩家的孩子,那么一旦我击中游戏,相机就会开始围绕对象旋转。

请给我一些提示我在做什么错?

由于您的起始方法上的较低情况,因此未设置摄像头偏移量。这意味着偏移保持其默认值为0,0,0,导致您的相机移至某个时髦的地方。

更改:`

void start() {
...
}

to

void Start() {
...
}

看到您不需要任何代码,只需使您的摄像机成为玩家对象的孩子。

将相机对象拖到层次结构中的播放器对象

最新更新