Unity 2D物体左右移动脚本(鼠标触摸+键盘)
using UnityEngine; using System.Collections; public class Paddle : MonoBehaviour { void Update() { if (GameManager.Instance.currentState == GameState.Playing && GameManager.Instance != null) { //鼠标或触摸 if (Input.GetMouseButton(0)) { //Create a ray from camera to playfield Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); Plane p = new Plane(Vector3.up, transform.position); //Shoot the ray to know where the click/tap found place in 3D float distance; if (p.Raycast(mouseRay, out distance)) { //Use current position as starting point Vector3 position = transform.position; //The player can only move the paddle in the x axis, so don't use the y and z position.x = mouseRay.GetPoint(distance).x; //GetPoint gives us the position in 3D //Apply the new position transform.position = position; } else { //The ray missed } } // 键盘 else if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) { //Use current position as starting point Vector3 position = transform.position; position.x = position.x - Time.deltaTime * 50; transform.position = position; } else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { //Use current position as starting point Vector3 position = transform.position; position.x = position.x + Time.deltaTime * 50; transform.position = position; } } //Make sure the paddle stays inside the level float freedom = 19.25F; Vector3 limitedPosition = transform.position; if (Mathf.Abs(limitedPosition.x) > freedom) { //Paddle is outside the level so move it back in limitedPosition.x = Mathf.Clamp(transform.position.x, -freedom, freedom); transform.position = limitedPosition; } } }
补充:
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/15033604.html
分类:
游戏开发-Unity
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
2020-07-20 配置C++中Opencv环境变量