Unity相机移动脚本+一些小玩意

自己无聊写的几个脚本,如果有兴趣都话可以看看首先是相机移动,相信刚学习Unity的同学对于相机的移动也是充满好奇吧?而想要实现相机的移动肯定是与鼠标脱不了关系的,毕竟pc上你还是需要通过鼠标来进行操控,Unity官方也知道我们的需求,所以给我们提供了虚拟轴的api,用起来也很是方便。float changeX = Input.GetAxis("Mouse X");float changeY = Input.GetAxis("Mouse Y");float mouseEnter = Input.Ge
摘要由CSDN通过智能技术生成

自己无聊写的几个脚本,如果有兴趣都话可以看看
首先是相机移动,相信刚学习Unity的同学对于相机的移动也是充满好奇吧?
而想要实现相机的移动肯定是与鼠标脱不了关系的,毕竟pc上你还是需要通过鼠标来进行操控,Unity官方也知道我们的需求,所以给我们提供了虚拟轴的api,用起来也很是方便。

float changeX = Input.GetAxis("Mouse X");
float changeY = Input.GetAxis("Mouse Y");
float mouseEnter = Input.GetAxis("Mouse ScrollWheel");

上面三行代码则是获取了三个虚拟轴,分别为鼠标的移动变量以及滑轮变量,三个虚拟轴都是返回一个float值,我们只需要在update中接收就行,有了这三个值我们就能简单的控制相机了,下面是整个相机控制脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.InteropServices;

public class CameraMove : MonoBehaviour
{
   
    public Camera camera;
    public static CameraMove instance;
    private void Awake()
    {
   
        instance = this;
    }
    private void Start()
    {
   
        camera = GetComponent<Camera>();
    }
    private void Update()
    {
   
        if (camera.enabled)
        {
   
            //鼠标中键相机移动
            if (Input.GetMouseButton(2))
            {
   
                float changeX = Input.GetAxis("Mouse X");
                float changeY = Input.GetAxis("Mouse Y");
                transform.Translate(Vector3.left * changeX );
                transform.Translate(Vector3.down * changeY );
            }
            //鼠标滑轮滑动相机镜头远近逻辑
            float mouseEnter = Input.GetAxis("Mouse ScrollWheel");
            transform.Translate(Vector3.forward * Time.deltaTime * mouseEnter * 700);
             //鼠标右键相机旋转逻辑
            if (Input.GetMouseButton(1))
            {
   
                float changeX = Input.GetAxis("Mouse X");
                float changeY = Input.GetAxis("Mouse Y");
                Vector3 camVec = transform.rotation.eulerAngles;
                Vector3 angleVec = new Vector3(-changeY * 2, changeX * 2, 0);
                camVec += angleVec;
                camVec = new Vector3(Mathf.Clamp(camVec.x, -85, 85), camVec.y, camVec.z);//限制角度,避免万向锁
                transform.eulerAngles = camVec;
            }
        }
    }
}

Mathf.Clamp(camVec.x, -85, 85)

在这里我为了避免万向锁特地对rotation的x轴进行了限定,直接用这个api就不用再去用if进行判定。

接下来是我随意写的一个物体生成脚本,通过鼠标点击“地面”并发射射线,最终在检测位置生成一个gameobject,并且可以给选中的物体进行旋转以及缩放,每个物体也是可以随意拖动!

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class CreateGame : MonoBehaviour
{
   
    public static CreateGame instance;
    private void Awake()
    {
   
        instance = this;
    }</
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值