gpt4 book ai didi

c# - 如何让一个对象在鼠标点击时移动并与另一个对象交换位置

转载 作者:行者123 更新时间:2023-11-30 13:54:37 25 4
gpt4 key购买 nike

到目前为止,我有一个脚本可以在单击鼠标时将对象移动一小段距离,但是我想更改它,以便在我单击该对象时,它与旁边的另一个对象交换位置,而不仅仅是小对象它现在移动的距离。我对如何执行此操作有点困惑,因为我是 unity 的新手。

 using UnityEngine;
using System.Collections;

public class NewBehaviourScript: MonoBehaviour
{
public float movementSpeed = 10;

void Update(){
if ( Input.GetMouseButtonDown(0))
{
transform.Translate(Vector3.right * movementSpeed * Time.deltaTime);
}


}
}

最佳答案

试试这个:

 using UnityEngine;
using System.Collections;

public class NewBehaviourScript: MonoBehaviour {
public GameObject objectA; //Needs to be initialized in the editor, or on Start
public GameObject objectB; //Needs to be initialized in the editor, or on Start
public float movementSpeed = 10;
private Vector3 posA = Vector3.zero; //Vector3.zero is for initialization
private Vector3 posB = Vector3.zero; //Vector3.zero is for initialization

void Update() {
if ( Input.GetMouseButtonDown(0)) {
posA = objectA.gameObject.transform.position;
posB = objectB.gameObject.transform.position;
objectA.gameObject.transform.position = posB;
objectB.gameObject.transform.position = posA;
}
}

}

这只是将每个对象的位置保存到 posA 和 posB 变量中,然后将 objectA 移动到 posB,将 objectB 移动到 posA。

-或-

现在,如果 objectB 始终是不同的对象(不是常量)并且您不确定如何找到最近的对象,则可以使用光线转换。将以下函数添加到您的代码中:

gamObject NearestObject () {
int dist;
int nearestIndex;
//Create an array to contain objects to be hit by the raycast
RaycastHit[] nearby;
//Hit all objects within 100 units with a raycast, change the 100 as needed
nearby = Physics.RaycastAll(objectA.transform.position, transform.forward, 100.0f);
//Check if there is at least one object
if(nearby.Length > 0) {
//If there is only one object and it's not objectA
if(!(nearby.Length == 1 && nearby[0].transform == objectA.transform)) {
dist = nearby[0].distance;
nearestIndex = 0;
for (int i = 1; i < nearby.Length; i++) {
if(nearby[i].transform != gameObject.transform && nearby[i].distance < dist)
dist = nearby[i].distance;
nearestIndex = i;
}
}
} else {
//There is only one object in the raycast and it is objectA
nearestIndex = -1;
}
} else {
//There are no objects nearby
nearestIndex = -1;
}
//nearestIndex will only be negative one if there are no objects near objectA, so return null
if (nearestIndex == -1) {
return null;
} else {
//return nearest object to update
return nearby[nearestIndex].gameObject;
}
}

最后,将更新更改为:

     void Update() {
if ( Input.GetMouseButtonDown(0)) {
objectB = NearestObject ();
if (objectB != null) {
posA = objectA.gameObject.transform.position;
posB = objectB.gameObject.transform.position;
objectA.gameObject.transform.position = posB;
objectB.gameObject.transform.position = posA;
}
}
}

关于c# - 如何让一个对象在鼠标点击时移动并与另一个对象交换位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com