UNITY | PROJECT | 2D PlatFormer | 3. Basic Enemy

2

3
“PlayerControl” Script
  • Create a bool variable isGrounded as Flag
  • Create OnCollisionEnter2D() method,
    • when a collision with an object tagged “Ground”
      • the flag is set to “true
4
Tagging “Ground”
4-1
Collision Detection Working
5
“PlayerControl” Script
  • in Update() method,
    • add code as a condition for Player to jump
    • when the button is pressed and at the same time the flag is true(Player is grounded)
  • in Jump() method,
    • add code to set the flag to false
6
Box not tagged
7
Ground Tagged

 

9-1
Jump
  • Player is not jumping on Box because Box is not tagged as Ground

 

 

8
Creating “Enemy”
  • Create Enemy
    • add BoxCollider
    • add RigidBody2D
    • add EnemyControl Script

 

9
“EnemyControl” Script
  • Create variables for Enemy‘s speed and direction
    • Enemy is moving horizontally only, so take care of X
  • in Update() method
    • access velocity property to move the gameObject by using GetComponent
10
“Enemy” Inspector | Public Variables

 

11
“EnemyControl” Script
  • in Update() method,
    • add RayCasting to perceive the obstacles
    • Physics2D.RaycastHit2D(vector2 origin, vector2 direction)
      • the origin where Ray is cast from is the current position of gameObject
      • the direction of casting the ray is only x
      • when the length of ray is less than 0.7,
        • activate Flip()
    • create a function, Flip(),
      • change the direction in x opposite whenever this function is called
12
“Enemy” Inspector
  • put Enemy in Igonore Raycast layer
  • set the speed

 

12-1
Enemy Moving

 

13
When layer is defualt

 

14-1

UNITY TUTORIAL | PHYSICS | 3D Physics | Detecting Collisions with OnCollisionEnter

UNITY TUTORIAL | PHYSICS | 3D Physics | Detecting Collisions with OnCollisionEnter

2
Box Prefab | RigidBody Attached

3

4
GameObject | Physics Material | RigidBody | Collision Detection Script
5
Physics Material for Friction and Bounciness
6
OnColliisonEnter(Collision) | CompareTag() | Destroy()
ezgif.com-video-to-gif
Collision Detection | Destroy