[英]Unity C# Make two Sprites move to each other
所以我是Unity的新手,但是创建了一个简单的2D游戏。 单击它们时,我需要使两个精灵相互移动。 我想使用附加到主摄像头的脚本,但可以接受其他建议。 谢谢朋友! 这是我的脚本:
public class MoveTo : MonoBehaviour { GameObject objectA = null; GameObject objectB = null; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)) { Ray rayOrigin = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if(Physics.Raycast(rayOrigin, out hitInfo)) { //Destroy (hitInfo.collider.gameObject); if(objectA == null) { objectA = hitInfo.collider.gameObject; } else{ objectB = hitInfo.collider.gameObject; } if(objectA != null && objectB != null) { //Need something to make them move towards each other here??? objectA = null; objectB = null; } } } } }
在我看来,移动其他游戏对象并在摄像机上附加脚本会破坏Unity中组件的基本概念。 如果要使对象平滑移动并且还能够同时移动多对对象,这也将非常困难。 您将需要某种类型的移动对象及其目的地的列表。 然后,您需要浏览相机脚本的更新功能中的列表,并更新子画面gameObjects的所有位置。
我认为最好将下面的简单中间脚本附加到sprite的gameObjects上。
using UnityEngine;
using System.Collections;
public class Tweener : MonoBehaviour {
public float tweenStopDistance = 0.2f;
public float tweenSpeed = 2.0f;
public Vector3 targetPosition = new Vector3();
void Start () {
targetPosition = transform.position;
}
void Update () {
if((transform.position - targetPosition).magnitude > tweenStopDistance){
transform.position += tweenSpeed * (targetPosition - transform.position).normalized * Time.deltaTime;
}
}
}
在这种情况下,您只需要计算相机脚本中的目标位置即可。
if(objectA != null && objectB != null)
{
// Calculate position in the middle
Vector3 target = 0.5f * (objectA.transform.position + objectB.transform.position);
// Set middle position as tween target
objectA.GetComponent<Tweener>().targetPosition = target;
objectB.GetComponent<Tweener>().targetPosition = target;
objectA = null;
objectB = null;
}
如果您的目标机器上有很多精灵,并且计算能力不足。 您也可以在运行时将脚本组件与gameObject.AddComponent
附加在一起,以gameObject.AddComponent
需要它的精灵。 附着可能很繁重,但是您不需要测试目标是否已经移动了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.