THE ROAD RUNNER TUTORIAL 6: COLLECTING THE SNAGS AND POWERUPS

Check out the gameplay of the finished game below:



In the previous post we added the snags and powerups to our game, however the player couldn't collect the objects. In this post we are going to give our Road Runner the ability to collect these powerups and snags. I mean collect the powerups and avoid the snag, and yeah, we will make the player playing the game pay if he collects the snags.

Create a C# script named PlayerControl, attach it to the 3rd Person Controller and add the below script to it:

using UnityEngine;
using System.Collections;

public class PlayerControl : MonoBehaviour {
 
 CharacterController controller;
 bool isGrounded= false;
 public float speed = 6.0f;
 public float jumpSpeed = 8.0f;
 public float gravity = 20.0f;
 private Vector3 moveDirection = Vector3.zero;

 //start 
 void Start () {
  controller = GetComponent<CharacterController>();
 }
 
 // Update is called once per frame
 void Update (){
  if (controller.isGrounded) {
   animation.Play("run");            //play "run" animation if spacebar is not pressed
   moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0);  //get keyboard input to move in the horizontal direction
   moveDirection = transform.TransformDirection(moveDirection);  //apply this direction to the character
   moveDirection *= speed;            //increase the speed of the movement by the factor "speed" 
   
   if (Input.GetButton ("Jump")) {          //play "Jump" animation if character is grounded and spacebar is pressed
    animation.Stop("run");
    animation.Play("jump_pose");
    moveDirection.y = jumpSpeed;         //add the jump height to the character
   }
   if(controller.isGrounded)           //set the flag isGrounded to true if character is grounded
    isGrounded = true;
  }

  moveDirection.y -= gravity * Time.deltaTime;       //Apply gravity  
  controller.Move(moveDirection * Time.deltaTime);      //Move the controller
 }

 //check if the character collects the powerups or the snags
 void OnTriggerEnter(Collider other)
 {
  if(other.gameObject.name == "Powerup(Clone)")
  {
   //do something
  }
  else if(other.gameObject.name == "Obstacle(Clone)")
  {
   //do something
   } 
  Destroy(other.gameObject);            //destroy the snag or powerup if colllected by the player
  
 }
}
The script is commented clearly and can be understood easily. To sum it up:
1. In the Start function, we assigned the CharacterController component to a variable.
2. In the Update function, we checked if the character is grounded and added a jump movement if spacebar is pressed. We also made sure that our character shouldn't jump if he's not grounded.
3. We also added the ability of movement to the character based on the input given by the user. The direction in the horizontal can be controlled by the left arrow and right arrow keys.
4. The OnTriggerEnter function takes a Collider parameter. We check if this collider is a powerup or a snag and add some functionality based on the collected item. NOTE: The difference between a trigger and a collider is that the collider physically occupies space. Collider physically collides and the trigger simply detects collision. 
5. Finally we destroy the collected gameobject. Save the script and attach it to the GameController object which we had created in the last post.

If you test the game, you will notice that our game looks more meaningful, but is still not complete, in fact, far from being completed.Now you might ask where the uncollected objects go! Well, yes. We have to destroy them as well. To do this simply create a cube and position it at (0, 1, -15) and scale it to (10, 1, 1). Rename the cube to something meaningful like TriggerZone.



Check the Is Trigger checkbox of the Box Collider component.


This will act as a destroyer, i.e. we will destroy the uncollected items once they pass through this cube(TriggerZone).

Create a C# script named TriggerZoneScript and add the below code:
void OnTriggerEnter(Collider other){
 Destroy(other.gameObject);
}
Save the script and attach it to the TriggerZone object. Now all the uncollected items will be destroyed once they come in contact with the TriggerZone.


Download the completed version of this game from the Resources page.

The Road Runner Tutorial 1: Setting Up The World
The Road Runner Tutorial 2: Setting Up The World Continued
The Road Runner Tutorial 3: Adding A Character To Our Game
The Road Runner Tutorial 4: Set The Ground Moving
The Road Runner Tutorial 5: Adding Snags and Powerups to Our Game
The Road Runner Tutorial 7: Adding Gameplay Logic
The Road Runner Tutorial 8: Creating a Custom GUI Skin
The Road Runner Tutorial 9: Creating a Pause Menu
The Road Runner Tutorial 10: Adding Countdown and Main Menu
The Road Runner Tutorial 11: Adding Sound Effects To Our Game
The Road Runner Tutorial 12: Porting The Game To Android
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

49 comments:

  1. Sir, I get this error
    Assets/Scripts/PlayerControl.cs(15,30): error CS0411: The type arguments for method `UnityEngine.Component.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly

    can you help me with this script
    //start
    void Start () {
    controller = GetComponent();
    }

    thanks

    ReplyDelete
    Replies
    1. Ah, my bad. It should be:
      controller = GetComponent();
      I should let it know what type of component is to be 'Got'. In our case it is a 'CharacterController' of our character.
      I am not sure how I missed this but thanks a ton for making me aware of this error in the script.
      Do let me know if there are any issues.
      Cheers :)

      Delete
    2. thanks a ton for your answer.
      I had already added "ControllerCharacter" and attach PlayerControl scrip to GameController

      but I got new error in the script like this

      "MissingComponentException: There is no 'CharacterController' attached to the "GameController" game object, but a script is trying to access it.
      You probably need to add a CharacterController to the game object "GameController". Or your script needs to check if the component is attached before using it.
      PlayerControl.Update () (at Assets/Scripts/PlayerControl.cs:20)"


      Do I have to attach CharacterController to GameController Hierarchy?

      thanks again,

      Delete
    3. thanks dude i Did it..This is the best tutorials on the internet so far...I have been searching this kind of tutorial for about a month. God bless you.....when its next part coming with main menu, score and gameover.

      Delete
    4. @aguskaifullana... You are supposed to attach the PlayerControl to the Character. I believe the character is named as "3rd Person Controller", attach the script to this character.

      Delete
    5. @Sohaib...We are glad that you found our tutorials useful. The next part will be posted this weekend.
      Cheers :)

      Delete
    6. thanks man i am waiting for next video.

      Delete
    7. Sir My Object Is Not Destroying And 3rd Person Controller movement is Also Disable

      Delete
  2. @Sujit oh my bad, I'm sorry.
    work great, thanks. waiting for next tuts.
    Cheers:)

    ReplyDelete
  3. Using the generic method `UnityEngine.Component.GetComponent()' requires `1' type argument(s) (CS0305) (Assembly-CSharp)
    I can't seem to get rid of this error

    ReplyDelete
    Replies
    1. kyle try that
      controller = GetComponent();

      Delete
    2. In line 15 of player control instead of charactercontroller it must be
      CharacterController

      Delete
    3. ok i tried this and still am getting the same error:

      //start
      void Start () {
      controller = GetComponent();
      } Error CS0305: Using the generic method `UnityEngine.Component.GetComponent()' requires `1' type argument(s) (CS0305) (Assembly-CSharp)

      i must be missing something else

      Delete
    4. I have updated the script. The problem is blogger doesn't recongize the less than and grater than symbol. Try copying and pasting the updated script, and it shud work fine

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hi I got a problem, in game while moving left or right the character and camera also moves

    ReplyDelete
    Replies
    1. Unless the camera has some script attached or the camera is the child object of some parent which has some script attached it shouldn't move. Or the camera might have been incorrectly assigned to some reference in another script and hence it might be moving. But in our game we have done none of these. I would request you to kindly check for these cases.

      Delete
    2. and is the character supposed to turn left (face to the left side) when you move left?

      Delete
    3. found out the bug I had 2 javascripts attached to my character, thanks for the help @Sujit Horakeri

      Delete
  6. the script in step 2 still isn't working for me I have tried all alterations that were in the previous comments an get the same error as kyle.

    ReplyDelete
  7. I figured it out thank you anyways just a simple typo not even paying attention

    ReplyDelete
    Replies
    1. Great that you figured it out. Do you mind letting us know where the error was so that it will be helpful for the other readers?

      Delete
  8. hello sir first of all i m thankful of your best tutorial .............can u help me i want to add something in these game but i dont know where i can and what........i want to change player speed according to collision of walls and banana

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hey man my issue is the triggerzone is destroying my player and is not invisible. but what it doesn't destroy though is the powerups and obstacles, i've made no deviations from your scripts.

      cheers mate.

      Delete
    2. Second issue is that for some reason, when i move my player, it sort of launches into the air in an awkward manner instead of just sideways. i've checked everything and their should be problems. :/

      Delete
  10. Where are all the codes. As the project discount.

    ReplyDelete
  11. Hello Sujit,

    I am currently a second year student at the University of Greenwich, studying Games Design and Development and have come across your 'Road Runner Tutorial' for Unity, which fits the needs of the game that I am to create for this years coursework. However, please do not misunderstand that I am creating an exact copy of your tutorial, I would like to adapt your scripts to fit my game.

    Seeing as my coursework will be released as a free commercial product, would you be able to give me permission in order to use some of your scripts?

    Yours sincerely,
    Diler Mehmet

    ReplyDelete
  12. hi sujit,

    thank u for ur tutorial........but i need ur help with triggerzone script man......after put the script as u given here it says that(all compiler error should be fixed).........i knw i need to wirte full code which starts from using unity engine ......as am not good in programming please give me full code

    ReplyDelete
  13. hi sujit,,

    finally i figured it out any ways thnks for u tutorial.....

    ReplyDelete
  14. Hi my teacher wanted to download the finished game from the resources page but they are just redirecting you to where dropbox says "link generating too much public traffic" can you please update the links?

    ReplyDelete
  15. Hi Sujit , I was trying to change the powerup and obstacle prefab (mat+tex) both and i did , but after adding them , they don't seem to be appearing anymore. I also added and double checked scripts. Can you help?

    ReplyDelete
  16. Hello bro i need a help plz help i have a this error on trigger zone script"A namespace can only contain types and namespace declarations" plz help me :(

    ReplyDelete
    Replies
    1. add OnTriggerEnter into TriggerZoneScript class

      Delete
  17. have a this error on trigger zone script"A namespace can only contain types and namespace declarations"
    Pleaseee help

    ReplyDelete
  18. hiii dear.....renderer.material is becoming blur in samsung TAb &S3...can u pls help me out

    ReplyDelete
  19. i am seeing error CS8025:parsing error

    ReplyDelete
  20. i am seeing error CS8025:parsing error

    ReplyDelete
  21. hi sir when i created triggerzone script and added the code i got this message

    Assets/Scripts/TriggerZoneScript.cs(1,6): error CS0116: A namespace can only contain types and namespace declarations

    pls help me

    ReplyDelete
  22. Hi, your tutorial has been very useful for me so far, but I get this error:
    Assets/Scripts/PlayerControl.cs(19,35): error CS1525: Unexpected symbol `<', expecting `identifier'
    I couldn't solve the problem. By the way, I'm using Unity 5 right now.
    Thanks

    ReplyDelete
  23. Hello Sujit. my player always fall if i play and the player added cgaracter controller. please help me

    ReplyDelete
  24. Hey i am following your tutorial and it is working a treat, I changed the player controller script to only move in 3 lanes, what I would like to know is if you could help me write a script that would pool and instantiate obstacles and powerups in those three lanes ?? I am new to Unity and scripting and I need to develop this for my Diploma course, TIA

    Damien

    ReplyDelete
  25. have a this error on trigger zone script"A namespace can only contain types and namespace declarations"
    Pleaseee help

    ReplyDelete
  26. I Created a C# script named PlayerControl, attach it to the 3rd Person Controller and added script but it didn't working. what can i do now? How to do it

    ReplyDelete
  27. I have encounter error in this code. Is there something wrong in this code? or missing?

    void OnTriggerEnter(Collider other){
    Destroy(other.gameObject);
    }

    ReplyDelete
  28. I have encounter an error in this code. Is there something wrong in this code? or missing?

    void OnTriggerEnter(Collider other){
    Destroy(other.gameObject);
    }

    ReplyDelete
  29. Assets/Scripts/PlayerControl.cs(21,14): error CS1061: Type `UnityEngine.Component' does not contain a definition for `Play' and no extension method `Play' of type `UnityEngine.Component' could be found. Are you missing an assembly reference?

    ReplyDelete