unity中控制相机跟随物体移动

unity中控制相机跟随物体移动

  1. Main Camera下添加组件(follow target)

  2. 脚本中定义

csharp 复制代码
public Transform trans;
  1. 将transform拖拽到trans中,让trans可以引用到transform数值(方式1)

  2. 因为属于当前GameObject下的脚本组件,不使用拖拽的方式的话,可以直接在代码中用下面方式获取到transform的数值(方式2)

csharp 复制代码
transform.position  //此方法是在父类的MonoBehaviour中定义
  1. 定义目标对象
csharp 复制代码
public GameObject player;
  1. 添加目标引用对象

  2. 脚本里添加相对位置的设置逻辑

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class followTarget : MonoBehaviour
{
    // public Transform trans;
    public GameObject player;
    private Vector3 offset;
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = player.transform.position + offset;
    }
}

到此可实现控制相机跟随物体移动!

相关推荐
雨落倾城夏未凉1 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫2 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫3 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6253 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902113 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠4 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
LinXunFeng5 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
唐青枫6 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech6 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf8 天前
C#摸鱼实录——IoC与DI案例详解
c#