鼠标框选角色

框选物品人物等等

1,需要设置的东西  选择这个模型并且 关闭Fill Center 直接就出现中空矩形,代码写好挂上即可

代码

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

public class BoxSelection : MonoBehaviour
{
public Camera cam;//获取摄像机
// Start is called before the first frame update
void Start()
{
cam = Camera.main;//此处获取主相机
}
Vector3 startpos;//开始拖拽时候的位置
bool isDrag = false;//是否拖拽
Rect rect;//矩形
// Update is called once per frame
void Update()
{

if (Input.GetMouseButtonDown(0))//按左键
{
startpos = Input.mousePosition;//获取开始拖拽时候鼠标位置
isDrag = true;//设置true
}
if (isDrag)
{
float w = Mathf.Abs(startpos.x - Input.mousePosition.x);//获取开始拖拽与当前位置的差值
float h = Mathf.Abs(startpos.y - Input.mousePosition.y);
GetComponent<RectTransform>().sizeDelta = new Vector2(w, h);//设置当前图片的宽高
float x = startpos.x < Input.mousePosition.x ? startpos.x + w / 2 : Input.mousePosition.x + w / 2;//判断向哪个方向拖拽
float y = startpos.y < Input.mousePosition.y ? startpos.y + h / 2 : Input.mousePosition.y + h / 2;
GetComponent<RectTransform>().anchoredPosition = new Vector2(x - Screen.width / 2, y - Screen.height / 2);//设置锚点位置 用比值
rect = new Rect(x - w / 2, y - h / 2, w, h);
}
if (Input.GetMouseButtonUp(0))
{
GetComponent<RectTransform>().sizeDelta = Vector2.zero;//清零
isDrag = false;
}
}
}

在实时战略游戏(RTS)中,框选玩家控制的角色通常涉及到鼠标交互和碰撞检测技术。在3D环境中,这需要结合输入处理、数学计算以及图形库的具体API。以下是一个简化的框架,假设使用的是Unity引擎: 1. **监听用户输入**:首先,你需要监听鼠标按下(MouseDown)、移动(MouseMove)和抬起(MouseUp)事件。 2. **初始化状态**:在游戏开始时,创建一个空的选定集(Selection Set),用于存储被框选的人物。 3. **鼠标点击事件处理**: - 当鼠标按下并处于选中模式(比如按住左键),获取当前鼠标的位置。 - 创建一个3D矩形框,其大小通常基于鼠标的当前位置和按下位置。这可以是视口空间(View Space)中的矩形,也可以是世界空间(World Space)中的矩形,取决于你的需求。 4. **碰撞检测**:使用Unity的Raycast或多边形碰撞检测功能,检查这个矩形框是否与游戏中的人物角色相交。如果相交,将该角色添加到选定集。 5. **鼠标移动事件处理**:如果鼠标还在按下状态下移动,更新矩形框的位置。如果移除鼠标,从选定集中移除所有角色。 6. **显示选定结果**:最后,在UI上展示选定的人物,或者在游戏中以某种方式突出显示它们。 ```csharp // 示例代码片段(简化版) public class SelectUnit : MonoBehaviour { public List<GameObject> selectedUnits = new List<GameObject>(); private void Update() { if (Input.GetMouseButton(0) && Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { // 碰撞检测 foreach (GameObject unit in selectedUnits) { if (unit.transform.Intersects(hit.collider.bounds)) { unit.SetActive(true); // 显示选中 } } // 更新框选矩形 SelectionBox = new BoundingBox(hit.point, hit.point + Vector3.Distance(hit.point, ray.direction) * hit.distance * Vector3.right); } } if (Input.GetMouseButtonUp(0)) { // 移除鼠标抬起后的选定 foreach (GameObject unit in selectedUnits) { unit.SetActive(false); } } } public BoundingBox SelectionBox; // 保存当前框选的矩形 } ``` 请注意,实际的实现可能更复杂,涉及更多细节,例如边界情况处理、性能优化等。同时,具体的代码可能会因所使用的引擎或库的不同而有所差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值