Unity摄像机跟随
普通跟随
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCam : MonoBehaviour
{
public Transform target;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
Vector3 newPos = target.position + offset;
transform.position = newPos;
}
}
插值去抖跟随
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCam : MonoBehaviour
{
public Transform target;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
Vector3 newPos = target.position + offset;
//Lerp插值,(位置1,位置2,0-1之间的数)
Vector3 pos = Vector3.Lerp(transform.position, newPos, 0.5f);
transform.position = pos;
}
}
LookAt 聚光灯跟随(相机位置不动)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCam : MonoBehaviour
{
public Transform target;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void Update()
{
//转向目标点
transform.LookAt(target);
}
}
普通移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float speed = 3.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 input = new Vector3(h, 0, v);
if (input.magnitude > 1)
{
input = input.normalized;
}
//考虑时间,抵消帧率变化的影响
transform.position += input * speed * Time.deltaTime; //世界坐标系
transform.Translate(input * speed * Time.deltaTime,Space.World);//世界坐标系
transform.Translate(input * speed * Time.deltaTime); //自身坐标系
transform.Translate(input * speed * Time.deltaTime,Space.Self); //自身坐标系
}
}
旋转式移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateMove : MonoBehaviour
{
public float speed = 3.0f;
public float rotateSpeed = 3.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//h控制旋转
transform.Rotate(new Vector3(0, h * rotateSpeed * Time.deltaTime, 0));
//v控制前进后退
transform.Translate(new Vector3(0, 0, v) * speed * Time.deltaTime);
}
}