我有一个预制件,当用户从我的游戏中商店购买物品时被实例化,无论有多少被实例化,所有的预制件都有一个特定位置的开始位置。可以使用我在网上找到的this TouchScript包在场景中拖动预制件!我的问题:每当用户在屏幕上拖动预制件时,我都想播放预制件的动画,我试图通过创建一个RaycastHit2D函数来检测用户是否点击了预制件的碰撞器,脚本如下:
if (Input.GetMouseButtonDown (0)) {
Vector2 worldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (worldPoint, Vector2.zero);
if (hit.collider != null) {
if (this.gameObject.name == "Item5 (1)(Clone)" +item5Increase.i) {
monkeyAnim.SetBool ("draging", true);
Debug.Log (hit.collider.name);
}
} else {
monkeyAnim.SetBool ("draging", false);
}
}但是,如果我要购买多个预制件,当我开始只拖动一个实例化的预制件时,所有实例化的预制件都会播放它的动画,希望我这样做是有意义的。有人能帮帮我吗?谢谢!
发布于 2018-08-01 10:04:44
在我的2D游戏中,我遇到了类似的平台问题。我建议的解决方案是创建一个GameObject,作为你想要动画的当前项目,以及一个LayerMask,作为你的光线投射可以命中的对象的过滤器。您可以将此LayerMask与Physics2D.Raycast API结合使用,后者有一个以LayerMask为参数的重载方法。
首先创建一个新的层,可以通过转到场景中对象的右上角并访问“层”框来完成。一旦你创建了一个新的层(我称之为我的“项目”),确保你的预制的层是正确分配的。
然后,在场景中创建一个空对象,并将此脚本附加到该对象。在该对象上,您将看到一个下拉菜单,询问您的光线投射应该命中哪些层。指定它的“项目”层;这确保你的光线投射只能击中该层中的对象,所以点击游戏中的任何其他东西都不会产生任何效果。
using UnityEngine;
public class ItemAnimation : MonoBehaviour
{
private GameObject itemToAnimate;
private Animator itemAnim;
[SerializeField]
private LayerMask itemMask;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
CheckItemAnimations();
}
else if (Input.GetMouseButtonUp(0) && itemToAnimate != null) //reset the GameObject once the user is no longer holding down the mouse
{
itemAnim.SetBool("draging", false);
itemToAnimate = null;
}
}
private void CheckItemAnimations()
{
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero, 1, itemMask);
if (hit) //if the raycast hit an object in the "item" layer
{
itemToAnimate = hit.collider.gameObject;
itemAnim = itemToAnimate.GetComponent<Animator>();
itemAnim.SetBool("draging", true);
Debug.Log(itemToAnimate.name);
}
else //the raycast didn't make contact with an item
{
return;
}
}
}https://stackoverflow.com/questions/51623764
复制相似问题