什么是基于鼠标悬停绘制矩形轮廓的正确方法。当选择单位时,您在策略游戏中获得的效果。运行Unity 2018.3.0f。也许我的代码可以稍微更改。我无法找到完成的东西。作为第二个选项,我可以使用LineRenderer并基于该线创建矩形。添加将使矩形的线条。
这是一个例子:
这是我想出来的,但由于某种原因,这有错误的Y坐标。
using UnityEngine;
using System.Collections;
using System;
public class MouseDragSelect : MonoBehaviour
{
private Rect position = new Rect(193, 148, 249-193, 148-104);
public Color color = Color.green;
private Vector3[] mousePositions = new Vector3[2];
private bool draggingMouse = false;
private bool drawRect = false;
public float timer = 1.2f;
void OnGUI()
{
if (drawRect)
{
DrawRectangle(position, 1, color);
}
}
void DrawRectangle(Rect area, int frameWidth, Color color)
{
//Create a one pixel texture with the right color
var texture = new Texture2D(1, 1);
texture.SetPixel(0, 0, color);
texture.Apply();
Rect lineArea = area;
lineArea.height = frameWidth; //Top line
GUI.DrawTexture(lineArea, texture);
lineArea.y = area.yMax - frameWidth; //Bottom
GUI.DrawTexture(lineArea, texture);
lineArea = area;
lineArea.width = frameWidth; //Left
GUI.DrawTexture(lineArea, texture);
lineArea.x = area.xMax - frameWidth;//Right
GUI.DrawTexture(lineArea, texture);
}
void reset() {
drawRect = false;
mousePositions[0] = new Vector3();
mousePositions[1] = new Vector3();
timer = 1.2f;
draggingMouse = false;
}
private void Update()
{
if (drawRect)
{
if (timer > 0.1)
{
timer -= 1 * Time.deltaTime;
} else {
reset();
}
}
if(Input.GetMouseButtonDown(0)) {
if(!draggingMouse){
mousePositions[0] = Input.mousePosition;
print("x start:" + mousePositions[0].x);
print("y start:" + mousePositions[0].y);
}
draggingMouse = true;
}
if(Input.GetMouseButtonUp(0)) {
if(draggingMouse) {
mousePositions[1] = Input.mousePosition;
float width = Math.Abs(mousePositions[1].x - mousePositions[0].x);
float height = Math.Abs(mousePositions[1].y - mousePositions[0].y);
float x = mousePositions[0].x;
float y = mousePositions[0].y;
// print("width:" + width);
// print("height:" + height);
print("x end:" + mousePositions[1].x);
print("y end:" + mousePositions[1].y);
position = new Rect(x, y, width, height);
// print("Got last mouse position!");
drawRect = true;
}
}
}
}
尝试选择字符周围的区域..获得奇怪的Y坐标..
以下解决方案也不起作用:(因为我得到了奇怪的Y坐标
float x = Math.Min(mousePositions[0].x, mousePositions[1].x);
float y = Math.Min(mousePositions[0].y, mousePositions[1].y);
float width = Math.Max(mousePositions[0].x, mousePositions[1].x) - x;
float height = Math.Max(mousePositions[0].y, mousePositions[1].y) - y;
3条答案
按热度按时间f4t66c6m1#
所以对于你y坐标,屏幕空间和世界空间在不同的屏幕上是不同的。把你的y改为Screen. height-mousePosition. y。这会帮你解决这个问题
vd8tlhqk2#
为了防止有人像我一样纠结于此,这里是解决方案,它似乎可以正常工作。该解决方案使用@Alex的初始代码和@Technivorous的调整。
oxosxuxt3#
关键问题是Technivorous建议的
Screen.height-mousePosition.y
,但是这个问题可以更简洁地解决: