我在游戏开发方面相当新,我有一段代码可以让玩家根据玩家的动作移动。 玩家的动作脚本:
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,0,0,导致相机移动到某个时髦的地方。
更改:`
void start() {
...
}
到
void Start() {
...
}