我有一个预制件,当用户从我的游戏内商店购买物品时被实例化,实例化了多少,所有预制件都具有某个特定位置的开始位置。可以使用我在网上找到的this TouchScript包将预制件拖到现场!我的问题:我想在用户每次在屏幕上拖动预制件时播放预制件的动画,我通过创建RaycastHit2D函数来尝试此操作,该函数使我能够检测用户是否单击了预制件的对撞机,脚本如下: / p>
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);
}
}
但是,如果我要购买多个预制件,那么当我开始只拖动其中一个实例化预制件时,所有实例化预制件都将播放其动画,希望这是有意义的。有人能帮我吗?谢谢!
答案 0 :(得分:2)
我在2D游戏中遇到了类似的平台问题。我建议的解决方案是创建一个GameObject
来充当您要设置动画的当前项目,并创建一个LayerMask
来充当您的射线投射可以命中的对象的过滤器。您可以将此LayerMask
与Physics2D.Raycast
API结合使用,后者具有以LayerMask
作为参数的重载方法。
首先创建一个新层,方法是转到场景中对象的右上角,然后访问“层”(Layer)框。创建新层(我称其为“项目”)后,请确保正确分配了预制层。
然后,在场景中创建一个空对象,并将此脚本附加到该对象。在该对象上,您将看到一个下拉菜单,询问您的光线投射应击中哪一层。给它分配“ item”层;这样可以确保您的光线投射只能命中该层中的对象,因此单击游戏中的其他任何内容都不会产生效果。
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;
}
}
}