栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

unity 简单的相机跟随和主角移动功能

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

unity 简单的相机跟随和主角移动功能

一:相机跟随原理:

unity相机跟随是一个很常见的需求,这里的原理就是相机的位置和主角的位置有个差 值,一旦主角移动相机根据这个插值进行更新相机的位置就好了,另外需要平滑变化相机的角度。

 主要是利用了Vector3.Lerp对位置进行插值,Quaternion.Slerp适合对角度进行插值。

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

public class PlayerFollowCamera : MonoBehaviour
{

    private Transform Player;

    public float speed = 1f;

    // Start is called before the first frame update
    void Start()
    {
        Player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 targetPos = this.Player.transform.position + new Vector3(0, 2.42f, -2.42f);
        transform.position = Vector3.Lerp(transform.position, targetPos, speed * Time.deltaTime);
        // 这两个位置不能反哦
        Quaternion targetRotation = Quaternion.LookRotation(Player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
    }
}

 二:主角移动,利用Input.GetAxis()来获得主角来具体朝向哪个方向,通常由两个参数:“Horizontal”,“Vertical”,

这里记作:float h = Input.GetAxis("Horizontal");float v = Input.GetAxis("Vertical");

h > 0 方向是世界坐标系下x轴的正方向 v> 0 方向是世界坐标系下的z轴的正方向。

1: 转向: 

        利用transform.LookAt(dir); 但是这个点dir并不是主角的位置,而是主角的位置加上向量(h,0,v)

2:移动:利用的是unity自带的组件CharacterController

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

public class PlayerController : MonoBehaviour
{

    private CharacterController cc;
    public float moveSpeed = 2f;
    // Start is called before the first frame update
    void Start()
    {
        cc = GetComponent();
    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        if(Mathf.Abs(h) >= 0.01 || Mathf.Abs(v) >= 0.01)
        {
            Vector3 dir = new Vector3(h, 0, v);

            transform.LookAt(transform.position + dir);

            cc.SimpleMove(transform.forward * moveSpeed);
            
        }

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/898087.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号