unity3d快速实现小地图功能(相机跟随)

实现效果

在这里插入图片描述


实现思路

  1. 创建Cube作为Player,场景拥有两个摄影机。一个(MainCamera)跟随玩家作为主视角,另一个(Camera1)作为我们的小地图从高空俯视角度跟随玩家
  2. 实现两个脚本,一个支持玩家移动,另一个实现摄像机跟随玩家

步骤

基础操作详见官方文档(链接)

  • 1.新建两个脚本(cameraFollow) 和(move):

move

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

public class move : MonoBehaviour
{   
    public Camera firstPersonCamera;
    public Camera overheadCamera;
    public bool status;
    public float moveSpeed;
    public bool zooming;
    public float zoomSpeed;
    
    // Start is called before the first frame update
    void Start()
    {
        status = true;
        moveSpeed = 50;
    }

    // Update is called once per frame
    void Update()
    {   
        // 玩家移动
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        transform.Translate(new Vector3(horizontalInput, 0, verticalInput) * moveSpeed * Time.deltaTime);
        //  键盘k按键控制小地图显示
        if (Input.GetKeyUp("k")) {
            if (status == true) {
                ShowOverheadView();
                status = false;
            } else {
                ShowFirstPersonView();
                status = true;
            }
        }
    }

    public void ShowOverheadView() {
        firstPersonCamera.enabled = false;
        overheadCamera.enabled = true;
    }

    public void ShowFirstPersonView() {
        firstPersonCamera.enabled = true;
        overheadCamera.enabled = false;
    }
}

cameraFollow

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

public class cameraFollow : MonoBehaviour
{   
    public Transform playerTransform;//跟踪的对象(Cube)
    private Vector3 offset;
    
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - playerTransform.position;//计算相对距离
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = playerTransform.position + offset; //保持相对距离
    }
}

  • 2.创建两个摄像机配置参考图片:
    在这里插入图片描述

  • 3.创建Cube(Player)配置参考图片:
    在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值