我已经用一个机器建模了多个零件。我希望能够在拖动鼠标左键的同时将部件“卡入”到位。如下面的视频:
http://www.youtube.com/watch?v=MKz7DdEH9mQ
这是我的代码:
JS
#pragma strict
var partnerName = "Hub";
var closeVPDist = 0.05;
var moveSpeed = 40.0;
var rotateSpeed = 90.0;
var closeColor = Color(1,0,0);
private var dist = Mathf.Infinity;
private var normalColor : Color;
private var partnerGO : GameObject;
function Start() {
normalColor = renderer.material.color;
partnerGO = GameObject.Find(partnerName);
}
function OnMouseDrag() {
var partnerPos = Camera.main.WorldToViewportPoint(partnerGO.transform.position);
var myPos = Camera.main.WorldToViewportPoint(transform.position);
dist = Vector2.Distance(partnerPos, myPos);
renderer.material.color = (dist < closeVPDist) ? closeColor : normalColor;
}
function OnMouseUp() {
if (dist < closeVPDist) {
transform.parent = partnerGO.transform;
InstallPart();
}
}
function InstallPart() {
while (transform.localPosition != Vector3.zero || transform.localRotation != Quaternion.identity) {
transform.localPosition = Vector3.MoveTowards(transform.localPosition, Vector3.zero, Time.deltaTime * moveSpeed);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.identity, Time.deltaTime * rotateSpeed);
yield;
}
}
通过单击GO并将其转到“伙伴”GO来工作...但我希望能够点击GO并将其拖动到正确的位置,然后将其捕捉到的地方。
编辑:
将以下脚本添加到每个对象,并结合之前的脚本让我更进一步。我现在需要弄清楚的是,如果没有足够接近合作伙伴GO,它们会重新回到原来的位置。想法?
C#
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown(){
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag(){
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
}