Question by
ameeraizat104 · Mar 27, 2020 at 11:34 AM ·
spawn points
spawn at specific set location/point/coordinate.
I create a game when the player hit the object, the object will spawn at specific location. my problem is the object spawn randomly and not at the specific position i want.
public class Ghost : MonoBehaviour { private Rigidbody2D rb; private float dirX, dirY, moveSpeed;
[SerializeField]
private GameObject pumpkin;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
moveSpeed = 5f;
SpawnPumpkin();
}
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal") * moveSpeed;
dirY = Input.GetAxisRaw("Vertical") * moveSpeed;
}
private void FixedUpdate()
{
rb.velocity = new Vector2(dirX, dirY);
}
private void SpawnPumpkin()
{
bool pumpkinSpawned = false;
while (!pumpkinSpawned)
{
Vector3 pumpkinPosition = new Vector3(Random.Range(-7f, 7f), Random.Range(-4f, 4f), 0f);
if ((pumpkinPosition - transform.position).magnitude < 3)
{
continue;
}
else
{
Instantiate(pumpkin, pumpkinPosition, Quaternion.identity);
pumpkinSpawned = true;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
Destroy(collision.gameObject);
SpawnPumpkin();
}
}
Comment
@ameeraizat104,
You set pumpkin position to a random location:
Vector3 pumpkinPosition = new Vector3(Random.Range(-7f, 7f), Random.Range(-4f, 4f), 0f);
And then you use pumpkinPosition for the spawn's location:
Instantiate(pumpkin, pumpkinPosition, Quaternion.identity);
Where is the problem?