团结,将预制件生成为“ nearestTarget”游戏对象的位置

问题描述 投票:-2回答:1

我正在创建一个正在创建对象的游戏。这些对象向左移动,并且玩家必须在对象到达屏幕末端之前按空格键。除了在移动物体上生成预制件外,其他所有东西都可以正常工作。

想法是在最近的目标上生成动画。但是当实例化时,预制件总是在预制件位置(0,0,0)实例化。如何在正确的位置制作实例化的预制件生成物? (我已经用print(nearestTarget.transform.position)进行了测试,根据“ nearestTarget”,打印总是给我一个不同的位置)

[尝试在HandSlapAnimation()方法中生成预制件。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInput : MonoBehaviour
{
    // Reference to levelManager
    [SerializeField] LevelManager levelManager;
    // Array of all present entities
    private GameObject[] targets;
    // Nearest entity
    private GameObject nearestTarget;
    // Array of all x position of all present entities
    private float[] locationOfTargets;
    // Nearest x position (transform.position.x) in all entities
    private float nearestLocation;
    // Finds the index location of the float value
    private int index;
    // Hand prefab to be instantiate during Keypress
    public GameObject handPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        targets = GameObject.FindGameObjectsWithTag("Entities");

        if (targets.Length > 0)
        {
            FindLocationOfEntities();
            AssignNearestTarget();
            HandSlapAnimation();
            DestroyNearestTarget();
        }
    }
}

void FindLocationOfEntities()
{
    locationOfTargets = new float[targets.Length];

    for (int i = 0; i < targets.Length; i++)
    {
        locationOfTargets[i] = targets[i].transform.position.x;
    }
}

void AssignNearestTarget()
{
    nearestLocation = Mathf.Min(locationOfTargets);
    index = System.Array.IndexOf(locationOfTargets, nearestLocation);
    nearestTarget = targets[index];
}

void DestroyNearestTarget()
{        
    if (nearestTarget.GetComponent<CubeMovement>().isCat == true)
    {
        levelManager.LoadLevel("Game Over");
    }
    else
    {
        Destroy(nearestTarget);
    }
}

void HandSlapAnimation()
{
    // Instantiate  prefab Hand GameObject at the nearest target to execute the Hand Slap animation
    Instantiate(handPrefab, transform.position, Quaternion.identity);
    handPrefab.transform.SetParent(nearestTarget.transform);
    print(nearestTarget.transform.position);
}

}

unity3d instantiation spawn
1个回答
0
投票

问题在于:

Instantiate(handPrefab, transform.position, Quaternion.identity);

transform.position是实际对象的位置,即您的PlayerInput实例。

然后,您执行:handPrefab.transform.SetParent(nearestTarget.transform),但不会移动位置,仅设置父级。

代替在transform.position方法中使用Instantiate,而使用nearestTarget.transform.position

Instantiate(handPrefab, nearestTarget.transform.position, Quaternion.identity);
© www.soinside.com 2019 - 2024. All rights reserved.