Unity限制相机移动范围,通过读取相机位置,对比下一帧位置是否超出范围,斜向走也不会卡住,判断移动方向的xyz轴分量哪个不超出移动限制范围,就让哪个分量生效。

项目中遇到要加一个Unity程序,而视角需要自由控制,然后又不能超出建模范围,不然就穿模了。

这里先通过方法读取键盘和鼠标,得到控制相机移动原始参数。

xL2, yL2, zL2为读取上一帧相机位置,xL, yL, zL,为移动后读取下一帧位置,靠近限制范围时,斜向走也不会卡住,判断移动方向的xyz轴分量哪个不超出移动限制范围,就让哪个分量生效。

说说其他不能用的方法:设定相机位置是可以用transform.position = new Vector3(x, y, z),但是这个坐标是相对于整个场景固定,不会随着视角转动而转动,控制就会乱。

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

public class CameraScript : MonoBehaviour
{
    public int speed = 20;
    float x1, y1, xL, yL, zL, xL2, yL2, zL2, xL3, yL3, zL3;
    // 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");
        float s = 0f;
        if (Input.GetKey("space"))
        {
            s = 1;
        }
        if (Input.GetKey("left ctrl"))
        {
            s = -1;
        }
        x1 += Input.GetAxis("Mouse X");
        y1 += -Input.GetAxis("Mouse Y");
        transform.rotation = Quaternion.Euler(y1, x1, 0);
        xL2 = transform.position.x;
        yL2 = transform.position.y;
        zL2 = transform.position.z;
        transform.Translate(new Vector3(h, s, v) * Time.deltaTime * speed);
        xL = transform.position.x;
        yL = transform.position.y;
        zL = transform.position.z;

            if (xL > 199 || xL < -199)xL3 = xL2;
            else xL3 = xL;
            if (yL > 14 || yL < 0.5)yL3 = yL2;
            else yL3 = yL;
            if (zL > 49 || zL < -49)zL3 = zL2;
            else zL3 = zL;

            transform.position = new Vector3(xL3, yL3, zL3);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
判断相机是否移动到指定地点,并在到达后继续移动到下一个指定地点,你可以使用以下方法: 1. 在Unity中,选择你的主相机,并将其添加到一个脚本组件中。 2. 在脚本中,创建一个公共变量来存储指定地点的位置,例如:public Transform[] targetPoints; 3. 在脚本中,创建一个私有变量来存储当前目标点的索引,例如:private int currentTargetIndex = 0; 4. 在脚本的Update函数中,使用Vector3.Distance函数来计算当前相机位置与目标点位置的距离,例如:float distance = Vector3.Distance(transform.position, targetPoints[currentTargetIndex].position); 5. 判断距离是否小于某个阈值来确定是否到达了目标点,例如:if (distance < 0.1f) { // 到达了目标点 }。 6. 如果到达了目标点,在if语句中更新当前目标点的索引,并确保索引不超过目标点数组的长度,例如:currentTargetIndex++; if (currentTargetIndex >= targetPoints.Length) { currentTargetIndex = 0; }。 7. 在if语句中更新下一个目标点的位置,例如:Vector3 nextTarget = targetPoints[currentTargetIndex].position; 8. 使用MoveTowards函数来平滑移动相机到下一个目标点,例如:transform.position = Vector3.MoveTowards(transform.position, nextTarget, speed * Time.deltaTime); 其中,speed是相机移动的速度。 这样,相机判断是否到达了指定地点,如果到达了,就继续移动到下一个指定地点。你可以在场景中设置多个指定地点,并在脚本的targetPoints数组中指定它们的位置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值