我正试图通过鼠标拖动来制作一个可调整大小的GameObject(在我的情况下是Quad(。我想让它工作如下:
- 检查鼠标位置是否在GameObject"边界"上
- 等待光标位于"边界"之外
- 只需调整大小(就像在图形软件中一样(
虽然我对第一步和第三步没有问题,但对第二步有一个令人困惑的问题。
我的代码目前正在做的是:
- 检查鼠标位置是否在GameObject"边界"上
- 只需调整大小
这意味着我没有第二步了。我以为我可以简单地通过等待第二个条件完成来解决它,但它没有起作用。
所以。。。我怎样才能让它按我想要的方式工作?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class ResizeObject : MonoBehaviour
{
public GameObject ground;
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
// If I click on the quad in a "border" area
if (Input.GetMouseButton(0) && mousePosition.x >= ground.transform.localScale.x / 2 - 0.1 && mousePosition.x <= ground.transform.localScale.x / 2)
{
// Wait until this condition (cursor is outside a border area) will be true???
if (mousePosition.x > ground.transform.localScale.x / 2)
{
// Reisze a quad
ground.transform.localScale = new Vector3(ground.transform.localScale.x / 2 + mousePosition.x, 1, 1);
}
}
}
}
假设这是您的四边形,以c为中心,h是其高度的一半,w则是其宽度的一半。
------- -
| | | h
| c | -
| |
'-------'
|---|
w
我不记得四边形是否有SpriteRenderer属性,但如果它有,你可以使用.bounds来获得w和h。否则,您可以附加一个BoxCollider2D(如果不需要的话,可以作为触发器(,并使用.bounds来获取这些值。
有了这些值,您可以定义一个值d。让我们调用鼠标位置m,当至少满足以下条件之一时,您将触摸边界:
- c.x-w-d<m.x<c.x-w+d和c.y-h<m.y<c.y+h
- c.x+w-d<m.x<c.x+w+d和c.y-h<m.y<c.y+h
- c.y-h-d<m.y<c.y-h+d和c.x-w<m.x<c.x+w
- c.y+h-d<m.y<c.y+h+d和c.x-w<m.x<c.x+w
您可以根据自己的意愿测试d,它越大,就越容易触摸边界。
要进行触摸,您可以使用内置方法(仅在连接了对撞机时可用(OnMouseDown
、OnMouseDrag
和OnMouseUp
。
缩放过程由您决定,但可以使用.bounds值进行简单的数学运算,从OnMouseDown
开始,在OnMouseDrag
缩放,到OnMouseUp
结束。