Unity&镜头跟随

实用系列(一) 简单的镜头跟随

功能介绍:

  1. 令相机跟随游戏物体;
  2. 按下Q,E可以左右旋转视角;
  3. 滚动鼠标滑轮可以放大或者缩小视角;

代码使用方法:

  1. 新建C#脚本FollowPlayer并挂载相机上,设置跟随物体的Tag值为Player;
  2. 调整当前Scene视角对准跟随物体,按下Ctrl + Shift + F(即Align With View),让相机视角对准跟随物体,设置好相关参数;
  3. 运行场景,相机即可跟随游戏物体移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour {

    private Transform player; // 跟随对象的初始位置
    private Vector3 offsetPosition; // 相机与对象的位置偏移
    private bool isRotating = false; // 是否旋转

    public float distance = 0;
    public float scrollSpeed = 3; // 拉进/拉远视角的速度
    public float rotateSpeed = 2; // 旋转速度

	void Start () {
            player = GameObject.FindGameObjectWithTag(Tags.player).transform; // 获取跟随物体的位置
            transform.LookAt(player.position);
            offsetPosition = transform.position - player.position;
	}
	
	void Update () {
            transform.position = offsetPosition + player.position;
            RotateView(); // 处理视野的旋转
            ScrollView(); // 处理视野的拉近和拉远效果   
        }

    void ScrollView() {
        // 向后滑动返回负值(拉远视野) 向前滑动返回正值(拉近视野)
        distance = offsetPosition.magnitude;
        distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
        distance = Mathf.Clamp(distance, 5, 10);
        offsetPosition = offsetPosition.normalized * distance;
    }

    void RotateView() {
        if (Input.GetKey(KeyCode.Q) || Input.GetKey(KeyCode.E)) {
            isRotating = true;
        }
        else {
            isRotating = false;
        }

        if (isRotating && Input.GetKey(KeyCode.Q)) {
            transform.RotateAround(player.position, Vector3.up, -rotateSpeed);
        }
        else if (isRotating && Input.GetKey(KeyCode.E)) {
            transform.RotateAround(player.position, Vector3.up, rotateSpeed);
        }
        offsetPosition = transform.position - player.position;
    }
}

Tags:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tags : MonoBehaviour {
	public static string player = "Player"; // 本人习惯如此保存所有的tag值
}

缺点:

  1. 每次手动更改游戏对象位置后,必须重新指定跟随视角(Ctrl + Shift + F)
  2. 若要Destroy跟随对象,需关闭此脚本,否则会报错
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值