Unity相机跟随-----根据速度设置偏移量

这里假设在水中的船,船有惯性,在不添加前进动力的情况下会继续移动,但是船身是可以360度自由旋转,当船的运动速度在船的前方的时候,相机会根据向前的速度的大小,设置相机的偏移量,从而提高游戏的动态带感。

但是由于惯性船的速度不一定在船的,因此可以获得当前船的速度方向在船的前方的投影分量,当分量与船的前方同向,那么设置偏移量为:速度分量的长度与船的最大比值t,乘以相机设定的最大偏移量

代码如下

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

public class CameraControl : MonoBehaviour {

    GameObject player;
    public float speed=10f;

最大偏移量,这里最好能保证角色在屏幕范围内
public float radius;// Use this for initialization void Start () { player = GameObject.FindWithTag("Player"); } // Update is called once per frame void Update () { Follow(); }void Follow() { if (!player) { player = GameObject.FindWithTag("Player"); } else { Rigidbody2D rigid= player.GetComponent<Rigidbody2D>(); Ship ship = player.GetComponent<Ship>(); Vector3 playerVelocity = rigid.velocity; //求出角色的速度在角色的正方向的分量速度 Vector3 playerVelocityOnForward= Vector3.Project(playerVelocity,player.transform.up); //得到分量速度的方向与正方向是否同符号 float dot = Vector3.Dot(playerVelocityOnForward, player.transform.up); //如果同符号,那么得到它的模与最大速度值的比值,用该比值乘以radius,即可得到相机的偏移位置量;如果不同号,即速度方向相反,那么比例值设置为0 float offsetLength = (dot >= 0 ? playerVelocityOnForward.magnitude / ship.maxSpeed : 0) * radius;
transform.position
= Vector3.Lerp (transform.position, player.transform.position + player.transform.up* offsetLength - Vector3.forward, Time.deltaTime * speed); } } }

猜你喜欢

转载自www.cnblogs.com/xiaoahui/p/10463746.html