当前位置:网站首页>【100个 Unity实用技能】| 游戏中获取鼠标点击的坐标,并将游戏对象移动到鼠标的点击位置
【100个 Unity实用技能】| 游戏中获取鼠标点击的坐标,并将游戏对象移动到鼠标的点击位置
2022-06-21 10:59:00 【华为云】

Unity 小科普
老规矩,先介绍一下Unity的科普小知识:
- Unity是 实时3D互动内容创作和运营平台 。
- 包括游戏开发、美术、建筑、汽车设计、影视在内的所有创作者,借助Unity将创意变成现实。
- Unity 平台提供一整套完善的软件解决方案,可用于创作、运营和变现任何实时互动的2D和3D内容,支持平台包括手机、平板电脑、PC、游戏主机、增强现实和虚拟现实设备。
- 也可以简单把 Unity 理解为一个游戏引擎,可以用来专业制作游戏!
Unity 实用小技能学习
游戏中获取鼠标点击的坐标,并将游戏对象移动到鼠标的点击位置
作用:在游戏中实现鼠标点击的时候,获取到鼠标点的的这个坐标,并将某个游戏对象移动到这个坐标上。
将脚本代码挂在场景中,并将希望跟随鼠标移动的对象拖到脚本上即可。
具体效果如下;
完整代码如下:
using UnityEngine;public class Vector3Test : MonoBehaviour{ [Header("需要跟随鼠标移动的游戏对象")] public GameObject targetPos; Vector3 screenPosition;//将物体从世界坐标转换为屏幕坐标 Vector3 mousePositionOnScreen;//获取到点击屏幕的屏幕坐标 Vector3 mousePositionInWorld;//将点击屏幕的屏幕坐标转换为世界坐标 private void LateUpdate() { if (Input.GetMouseButton(0)) { MouseFollow(); } } /// <summary> /// 获取鼠标点击坐标的方法 /// </summary> public Vector3 MouseFollow() { //获取游戏对象在世界坐标中的位置,并转换为屏幕坐标; screenPosition = Camera.main.WorldToScreenPoint(targetPos.transform.position); //获取鼠标在场景中坐标 mousePositionOnScreen = Input.mousePosition; //让鼠标坐标的Z轴坐标 等于 场景中游戏对象的Z轴坐标 mousePositionOnScreen.z = screenPosition.z; //将鼠标的屏幕坐标转化为世界坐标 mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen); //将游戏对象的坐标改为鼠标的世界坐标,物体跟随鼠标移动 targetPos.transform.position = mousePositionInWorld; //物体跟随鼠标X轴移动 return new Vector3(mousePositionInWorld.x, mousePositionInWorld.y, mousePositionInWorld.z); }}
边栏推荐
猜你喜欢

从零走进软件开发的世界

Why does C throw exceptions when accessing null fields?

Es composite query workload evaluation

Compilation principle knowledge points sorting
[Architect (Part 38)] locally install the latest version of MySQL database developed by the server

Research and implementation of embedded software framework based on multi process architecture

高性能并行编程与优化 | 第01讲回家作业

qmlbook学习总结

性能优化——图片压缩、加载和格式选择

C语言初阶(九)枚举
随机推荐
深水区涉入
游戏机之AR机械臂
Map集合遍历,添加替换,删除元素
Financial institutions scramble for "digital employees"; Release of aging service evaluation framework for insurance app
巴比特 | 元宇宙每日必读:微信或首次以“涉数字藏品二级交易”为由封禁一公众号,平台新规也对此提出警告...
06. Redis log: the trump card for fast recovery without fear of downtime
support vector machine
编译原理知识点整理
Compilation principle knowledge points sorting
Introduction to ThreadPoolExecutor
Young people are reluctant to change their mobile phones, because they choose a more durable iPhone, and the parameter theory of domestic mobile phones is invalid
3000帧动画图解MySQL为什么需要binlog、redo log和undo log
Regression analysis - basic content
运控入门到 Fang Si
Mqtt of NLog custom target
MySQL 5.7都即将停只维护了,是时候学习一波MySQL 8了
Feature metric loss for self supervised learning of depth and egomotion
C语言初阶(十)类型重命名typedef
Revenue of Fortinet will increase by 29% in 2021 founder Xieqing talks about the future of network security industry
Swift 之返回按钮