在Unity官网教程SurvivalShooter(恶魔射手)中,只处理了主角跟随鼠标旋转,摄像机视野并没有旋转或通过滚轮实现视野的拉远拉近,一下是我的实现方法。
在教程中,主角的移动是通过
//void Move(float h, float v)
//{
// movement.Set(h, 0f, v);
// movement = movement.normalized * speed * Time.deltaTime;
// playerRgidBody.MovePosition(transform.position + movement);
// PlayAnimation(h, v);
// PlayerTurning(h, v);
//}
实现的,他只能实现世界坐标系中x轴方向和z轴方向的移动(我的理解),以下是玩家的代码:
void FixedUpdate()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
//Move(h, v);
if (Input.GetKey(KeyCode.W))
{
MoveForward();
}
if (Input.GetKey(KeyCode.S))
{
MoveBack();
} if (Input.GetKey(KeyCode.A))
{
MoveLeft();
}
if (Input.GetKey(KeyCode.D))
{
MoveRight();
}
PlayAnimation(h, v);
PlayerTurning(h, v);
}
void MoveForward()
{
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
void MoveBack()
{
transform.Translate(Vector3.forward * Time.deltaTime * -speed);
}
void MoveLeft()
{
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
void MoveRight()
{
transform.Translate(Vector3.left * Time.deltaTime * -speed);
}
void PlayAnimation(float h, float v)
{
bool IsWalking = h != 0 || v != 0;
anim.SetBool("IsWalking", IsWalking);
}
void PlayerTurning(float h, float v)//人物跟随鼠标旋转
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, camRayLength, floorMask))
{
Vector3 playerToMouse = hit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
playerRgidBody.MoveRotation(newRotation);
}
}
以下是摄像机的代码:
void Start()
{
offset = transform.position - target.position;
}
void Update()
{
Vector3 currentPosition = target.position + offset;
transform.position = Vector3.Lerp(transform.position,
currentPosition, smoothing * Time.deltaTime);
RotateView();
ScrooView();
}
void ScrooView()//处理视野的拉近和拉远效果
{
Distance = offset.magnitude;
Distance += -Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
Distance = Mathf.Clamp(Distance, 5, 23);
offset = offset.normalized * Distance;
}
void RotateView()//处理视野的选转
{
if (Input.GetMouseButtonDown(1))
{
isRotating = true;
}
if (Input.GetMouseButtonUp(1))
{
isRotating = false;
}
if (isRotating)
{
Vector3 originalPosition = transform.position;
Quaternion originalRotation = transform.rotation;
transform.RotateAround(target.position, target.up, Input.GetAxis("Mouse X") * rotateSpeed);
transform.RotateAround(target.position, transform.right, -Input.GetAxis("Mouse Y") * rotateSpeed);
float x = transform.eulerAngles.x;
if (x < 10 || x > 80)//防止前后旋转角度过大
{
transform.position = originalPosition;
transform.rotation = originalRotation;
}
offset = transform.position - target.position;
}
}
通过此方法,即可实现旋转视野、摄像机跟随主角移动和旋转。
如有错误,欢饮指正。