Friday, June 22, 2018

c# - Unity - Random Spawned Enemy Is Not Moving


I want to make an enemy spawner with random rotation left and right in unity. Its an 2d platformer. The random rotation is working, but the enemy is not moving after it's spawned.


I put the rigidbody of the enemy in the value enemiesrb in the script EnemySpawn and gave it an .velocity = new Vector.


I have 2 scripts




EnemyPatrol:



public float moveSpeed;
public bool moveRight;

public Transform wallCheck;
public float wallCheckRadius;
public LayerMask whatIsWall;
private bool hitWall;


public float lockPos = 0;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update() {


hitWall = Physics2D.OverlapCircle(wallCheck.position, wallCheckRadius, whatIsWall);


if (hitWall)
{
moveRight = !moveRight;
}



if (moveRight)
{
transform.localScale = new Vector3(-1f, 1f, 1f);
//GetComponent().velocity = new Vector2(moveSpeed, GetComponent().velocity.y);
}
else
{
transform.localScale = new Vector3(1f, 1f, 1f);
//GetComponent().velocity = new Vector2(-moveSpeed, GetComponent().velocity.y);
}



and EnemySpawn



public GameObject enemies;
private Rigidbody2D enemiesrb;

public float spawnTime;
public int maxEnemies;
public int lofr;


private int amount;

public float moveSpeed;
void Start()
{
enemiesrb = enemies.GetComponent();
}



void Update()
{
//enemies = GameObject.FindGameObjectsWithTag("Enemy");
//amount = enemies.Length;

if (amount != maxEnemies)
InvokeRepeating("spawnEnemy", spawnTime , spawnTime);

}


void spawnEnemy()
{
lofr = Mathf.Abs(Random.Range(0, 1));

if (lofr == 1)
{
Instantiate(enemies , transform.position, Quaternion.Euler(1,180,1));
enemiesrb.velocity = new Vector2(moveSpeed, GetComponent().velocity.y);
}
else if(lofr == 0)

{
Instantiate(enemies , transform.position, Quaternion.Euler(1,1,1));
enemiesrb.velocity = new Vector2(-moveSpeed, GetComponent().velocity.y);
}
CancelInvoke();
}

the lofr means left or right. it defined if it need to spawn left or right




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...