Question by
gabryfigo9 · Jan 09, 2020 at 01:48 PM ·
movement scriptspawningspawning problemsenemy spawn
Problem with the enemy spawn,Problem with enemy
Hi, i made a script that let enemy spawn randomly around the player and also a script for the enemy for follow the player position.If i spawn manually the enemy they follow the player, but if i let the enemy to spawn from the spawn point they don't go toward the player. (sorry if bad english it's not my native language). P.S. i'm really a beginner.
This is the code for the enemy movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Transform player;
public float moveSpeed = 5f;
private Rigidbody2D rb;
public Vector2 movement;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
moveCharacter(movement);
}
void moveCharacter (Vector2 direction)
{
rb.MovePosition((Vector2) transform.position + (direction * moveSpeed * Time.deltaTime));
}
}
This is the code for the enemy spanwpoint:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawnerXDOWN : MonoBehaviour
{
public GameObject enemy;
float randX;
Vector2 spawnPoint;
public float spawnRate = 2f;
float nextSpawn = 0.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
randX = Random.Range(-42f, 46f);
spawnPoint = new Vector2(randX, transform.position.y);
Instantiate(enemy, spawnPoint, Quaternion.identity);
}
}
}
Comment