我目前正在Unity中开发游戏,但有一个问题。生成我创建的预制件的新克隆时,我希望实例化的游戏对象移动到其他游戏对象在其生成时所处的位置。这意味着通过设计,我需要使同一游戏对象/预制件的不同实例表现不同或移动到不同位置,即使它们同时处于活动状态也是如此。但是,当走入低谷时,我不得不动脑筋,只能解决极其复杂且非常耗费资源的解决方案(例如,创建列表字典,每个列表都包含在创建过程中创建的游戏对象,然后使速度可变对于不同的列表ext ...),其行为也有所不同。但是,我觉得必须有一个更简单,更省资源的解决方案,因为我发现这类问题一直在游戏中得到解决。有人知道我能做什么吗?
这是负责移动游戏对象实例的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractMovement : MonoBehaviour
{
Rigidbody2D rb;
GameObject target;
float moveSpeed;
Vector3 directionToTarget;
Renderer m_Renderer;
void Start()
{
if (ScoreScript.scoreValue > 4)
{
target = GameObject.Find("White Ball");
rb = GetComponent<Rigidbody2D>();
moveSpeed = 5f; //Movement speed of all the obstacles and powerups
InvokeRepeating("MoveInteract", 0f, 1f);
}
}
void MoveInteract() //Method responsable for the movement of the obstacles and stars
{
if ( this.gameObject != null)
{
directionToTarget = (target.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
directionToTarget.y * moveSpeed);
}
else
rb.velocity = Vector3.zero;
}
}
这是用于创建相关游戏对象实例的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BallSpawnerControl : MonoBehaviour
{
public Transform[] spawnPoints;
public GameObject[] interact;
int randomSpawnPoint, Interact;
int index = 1;
public static bool spawnAllowed;
// Use this for initialization
void Start()
{
spawnAllowed = true;
InvokeRepeating("SpawnAInteract", 0f, 1f);
}
void SpawnAInteract()
{
if (spawnAllowed)
{
if (index % 5 != 0)
{
randomSpawnPoint = Random.Range(0, spawnPoints.Length);
Interact = 1;
Instantiate(interact[Interact], spawnPoints[randomSpawnPoint].position,
Quaternion.identity);
index++;
}
else
{
randomSpawnPoint = Random.Range(0, spawnPoints.Length);
Interact = 0;
Instantiate(interact[Interact], spawnPoints[randomSpawnPoint].position,
Quaternion.identity);
index++;
}
}
}
}
“球”和“星星”(随后的游戏对象)应移至白球创建时所保持的位置,而不是改变其方向,使其移向白球的新方向,即MoveInteract。
答案 0 :(得分:1)
尝试在开始时将其目标位置存储在Vector3变量中
Vector3 position;
void Start()
{
if (ScoreScript.scoreValue > 4)
{
target = GameObject.Find("White Ball");
rb = GetComponent<Rigidbody2D>();
position = target.transform.position;
moveSpeed = 5f; //Movement speed of all the obstacles and powerups
InvokeRepeating("MoveInteract", 0f, 1f);
}
}
void MoveInteract() //Method responsable for the movement of the obstacles and stars
{
if ( this.gameObject != null)
{
directionToTarget = (position - transform.position).normalized;
rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
directionToTarget.y * moveSpeed);
}
else
rb.velocity = Vector3.zero;
}