For Week 2 of production, I had 2 priorities; Start work on the enemy and the enemy movement, and create a gun for the player.
I decided to work first on the enemy. This was relatively easy to complete. I created a new gameObject with a Rigidbody2D component, a Box Collider 2D component, and I created a script named "e1Movement."
Here is the spotPlayer that runs on the FixedUpdate function.
private void spotPlayer()
{
float playerDistance = Vector2.Distance(transform.position, _p1Movement.transform.position);
Debug.Log(playerDistance);
// Occurs if the player's calculated distance is greater than the allotted distance.
if (playerDistance > maxDistance)
{
_rigidbody2D.MovePosition(Vector2.MoveTowards(transform.position, _p1Movement.transform.position, enemySpeed * Time.deltaTime));
}
else if (playerDistance < maxDistance)
{
_rigidbody2D.velocity = new Vector2(0, 0);
}
}
As you can see, the function calculates the distance of the player from the enemy, if the gap is big enough, the enemy's Rigidbody2D moves towards the player. Otherwise, the velocity is set to 0.
Next, I focused on the player's shooting mechanic.
void Update()
{
gunBarrelUpdate();
if (Input.GetButtonDown("Fire1"))
{
BulletCreation();
}
}
void BulletCreation()
{
GameObject projectile = Instantiate(bullet, gunBarrel.position, gunBarrel.rotation);
Rigidbody2D bulletRb = projectile.GetComponent<Rigidbody2D>();
bulletRb.AddForce(gunBarrel.up * bulletImpact, ForceMode2D.Impulse);
}
I will get to the gunBarrelUpdate() function next, but the BulletCreation function creates a bullet projectile, finds the Rigidbody2D component and uses it to add a force to the bullet.
One problem I had was that the gun location wouldn't update in line with the player's direction.
void gunBarrelUpdate()
{
p1Direction = _p1movement.GetPlayerDirection();
if (p1Direction.x == 0 && p1Direction.y == -1) // South.
{
gunBarrel = South.transform;
}
else if (p1Direction.x == 0 && p1Direction.y == 1) // North.
{
gunBarrel = North.transform;
}
else if (p1Direction.x == 1 && p1Direction.y == 0) // East.
{
gunBarrel = East.transform;
}
else if (p1Direction.x == -1 && p1Direction.y == 0) // West.
{
gunBarrel = West.transform;
}
else
{
gunBarrel = originalGunPosition;
}
}