【问题标题】:unity3d: Camera does not follow the playerunity3d:相机不跟随玩家
【发布时间】:2016-11-24 06:27:39
【问题描述】:

我是游戏开发的新手,我有一段代码可以根据玩家的移动使相机移动。 玩家移动脚本:

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);            

}
}

但是当我将脚本附加到我的主摄像机时,一旦我进行测试,即使玩家尚未移动,游戏摄像机也会开始重新定位并移向地面。如果我从相机中删除脚本并使相机成为玩家的孩子,一旦我点击播放,相机就会开始围绕对象旋转。

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

【问题讨论】:

  • 您是否通过检查器将播放器附加到相机脚本?
  • 是的,我通过检查器附加了它

标签: unity3d


【解决方案1】:

由于您的 start 方法是小写字母,因此未设置相机偏移量。这意味着偏移量保持在其默认值 0,0,0 导致您的相机移动到某个时髦的地方。

更改:`

void start() {
...
}

void Start() {
...
}

【讨论】:

  • 仍然是相同的行为,但这次相机的位置向地面变化的速度较慢。
  • 您的启动功能是否正在运行?偏移位置对我来说似乎很好。我会调试玩家位置和偏移量,看看它们是否正确。
  • 尝试在相机脚本中将 start() 更改为 Start(),如果相机正向地面移动,那么您的偏移量似乎没有设置,因此保持在 0,0,0。
  • 将其更改为 Start() 是关键。谢谢你。将开始更改为开始后,Lerp 似乎表现正确
猜你喜欢
  • 2015-12-12
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多