Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by AlejandroBoss · Jan 24, 2017 at 05:11 PM · script.timespeedstoppowerup

How to make my powerup last for about five seconds then go back to normal?

Hey guys, I've made a PacMan and I've got a powerup that speeds you up. But what I need help with is that I only want it to last about 5 seconds then it returns to normal speed. The game is in 2D if that matters which I doubt it. Here is my script below.

using UnityEngine; using System.Collections; using UnityEngine.UI;

public class PacmanMove : MonoBehaviour { public float speed = 0.4f; Vector2 dest = Vector2.zero; public Text countText; private int count; private Rigidbody2D rb;

 void Start()
 {
     dest = transform.position;
     rb = GetComponent<Rigidbody2D>();
     count = 0;
     SetCountText();

 }

 void FixedUpdate()
 {
     // Move closer to Destination
     Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
     GetComponent<Rigidbody2D>().MovePosition(p);

     // Check for Input if not moving, this is also all the movement
     if ((Vector2)transform.position == dest)
     {
         if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
             dest = (Vector2)transform.position + Vector2.up;
         if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
             dest = (Vector2)transform.position + Vector2.right;
         if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
             dest = (Vector2)transform.position - Vector2.up;
         if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
             dest = (Vector2)transform.position - Vector2.right;
     }

     // Animation Parameters
     Vector2 dir = dest - (Vector2)transform.position;
     GetComponent<Animator>().SetFloat("DirX", dir.x);
     GetComponent<Animator>().SetFloat("DirY", dir.y);
 }

 bool valid(Vector2 dir)
 {
     // Cast Line from 'next to Pac-Man' to 'Pac-Man'
     Vector2 pos = transform.position;
     RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
     return (hit.collider == GetComponent<Collider2D>());
 }

 void  OnTriggerEnter2D(Collider2D other)
 {
     if (other.gameObject.CompareTag("Pacdot"))
     {
         other.gameObject.SetActive(false);
         count = count + 10;
         SetCountText();
     }

     // if Pacman collides with "PowerUp" his speed becomes that
     if (other.gameObject.CompareTag("PowerUp"))
     {
         speed = 2f;
     }
 }

 //shows the score that you have from the PacDots
 void SetCountText()
 {
     countText.text = "Count: " + count.ToString();
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by PizzaPie · Jan 24, 2017 at 05:38 PM

Use a coroutine

 IEnumerator PowerUp()
     {
         speed = 2f;
         yield return new WaitForSeconds(5f);
         speed = 1f;
         
     }

And Call it OnTriggerEnter() where you have the speed =2f like this:

     if (other.gameObject.CompareTag("PowerUp"))
          {
            StopCoroutine(PowerUp());  
            StartCoroutine(PowerUp());
          }

Now in case you encounter a 2nd PowerUp before the first is finished it will stop the first and initiate a second one. Of course if you don't want that behaviour and want the PowerUp only to last 5 secs even if you pick one more, while on the effect is on, then you need a bool to determine if you are on a PowerUp or not. Hope that helps.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AlejandroBoss · Jan 24, 2017 at 09:39 PM 0
Share

I'm curious as to where I would insert those two pieces of code. If possible could you tell me and be specific. I'm not sure where to insert those two pieces of code. On what line(s) should I insert that code. Also do I have to delete some code? Is it like this.

void Start() { dest = transform.position; rb = GetComponent(); count = 0; SetCountText(); } void FixedUpdate() { // $$anonymous$$ove closer to Destination Vector2 p = Vector2.$$anonymous$$oveTowards(transform.position, dest, speed); GetComponent().$$anonymous$$ovePosition(p); // Check for Input if not moving, this is also all the movement if ((Vector2)transform.position == dest) { if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.UpArrow) && valid(Vector2.up)) dest = (Vector2)transform.position + Vector2.up; if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.RightArrow) && valid(Vector2.right)) dest = (Vector2)transform.position + Vector2.right; if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.DownArrow) && valid(-Vector2.up)) dest = (Vector2)transform.position - Vector2.up; if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftArrow) && valid(-Vector2.right)) dest = (Vector2)transform.position - Vector2.right; } // Animation Parameters Vector2 dir = dest - (Vector2)transform.position; GetComponent().SetFloat("DirX", dir.x); GetComponent().SetFloat("DirY", dir.y); } bool valid(Vector2 dir) { // Cast Line from 'next to Pac-$$anonymous$$an' to 'Pac-$$anonymous$$an' Vector2 pos = transform.position; RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos); return (hit.collider == GetComponent()); } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Pacdot")) { other.gameObject.SetActive(false); count = count + 10; SetCountText(); } // if Pacman collides with "PowerUp" his speed becomes that

IEnumerator PowerUp() { speed = 2f; yield return new WaitForSeconds(5f); speed = 1f;

  }

  if (other.gameObject.CompareTag("PowerUp"))
  {
      StopCoroutine("PowerUp());
      StartCoroutine(PowerUp());
  }

} //shows the score that you have from the PacDots void SetCountText() { countText.text = "Count: " + count.ToString(); }

avatar image PizzaPie AlejandroBoss · Jan 25, 2017 at 12:09 AM 0
Share

The Ienumarator PowerUp() as it is a function you can place it wherever inside the class but outside of any other functions. And on the existing code on OnTriggerEnter() replace the lines 52-56 (below the comment // if Pacman collides with "PowerUp" his speed becomes that) with the code i wrote above. (if i am not mistaken in the above code(in comment, the badly edited code) you placed the PowerUp() function inside the OnTriggerEnter() if so it shouldn't be there it should be outside but still inside the class scope. If that is not enough clear let me know. Cheers

avatar image
0

Answer by crare · Jan 24, 2017 at 08:32 PM

You could use boolean for determining if powerup state is on. or int/string with multiple states for like normal, faster speed, bigger jump.. etc.. and check the state with if statement and do the stuff inside it. You can use simple timer/counterdown while the powerup is on.

 int state = 0; // 0 = normal, 1 = faster
 public float speedupgrade  = 2f;
 public float normalspeed = 1f;
 private float speed;
 float speedUpgradeLeft = 0;
 public float speedUpgradeLenght = 5f; //5 seconds
 ...

 ...
 if(state == 1) { // or you could use switch-statement if you have many states
     speed = normalspeed + speedupgrade; // 1f + 2f = 3f
 } else if (state == 2) {
      // do other stuff
 } else {
     speed = normalspeed; // 1f
 }
 
 // then just use speed variable
 Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);

  // then use timer to change state
  if(speedUpgradeLeft  > 0) {
       speedUpgradeLeft -= Time.deltatime;
  }
  else {
      state = 0;
  }
 ...

 ...
 //On your powerup trigger:
 // then trigger speedupgrade by setting time on it.
 speedUpgradeLeft = speedUpgradeLenght;
 // or adding more time on it
 speedUpgradeLeft += speedUpgradeLenght;
 // And change the state accordingly
 state = 1;
 ...
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by AlejandroBoss · Jan 27, 2017 at 07:46 PM

I'm soo confused @PizzaPie. I'm not the best coder so I don't understand the vocabulary that you were using. I know that I have to put it the couritine somewhere but I don't know when. Would you be clearer or, (i know this isn't really helping,) could you just do it for me. I mean that in the nicest way possible. I honestly have no idea where to put the script that you gave me.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image PizzaPie · Jan 27, 2017 at 08:05 PM 0
Share
 void Start()
 {
     dest = transform.position;
     rb = GetComponent<Rigidbody2D>();
     count = 0;
     SetCountText();
 }
 void FixedUpdate()
 {
     // $$anonymous$$ove closer to Destination
     Vector2 p = Vector2.$$anonymous$$oveTowards(transform.position, dest, speed);
     GetComponent<Rigidbody2D>().$$anonymous$$ovePosition(p);
     // Check for Input if not moving, this is also all the movement
     if ((Vector2)transform.position == dest)
     {
         if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.UpArrow) && valid(Vector2.up))
             dest = (Vector2)transform.position + Vector2.up;
         if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.RightArrow) && valid(Vector2.right))
             dest = (Vector2)transform.position + Vector2.right;
         if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.DownArrow) && valid(-Vector2.up))
             dest = (Vector2)transform.position - Vector2.up;
         if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftArrow) && valid(-Vector2.right))
             dest = (Vector2)transform.position - Vector2.right;
     }
     // Animation Parameters
     Vector2 dir = dest - (Vector2)transform.position;
     GetComponent<Animator>().SetFloat("DirX", dir.x);
     GetComponent<Animator>().SetFloat("DirY", dir.y);
 }
 bool valid(Vector2 dir)
 {
     // Cast Line from 'next to Pac-$$anonymous$$an' to 'Pac-$$anonymous$$an'
     Vector2 pos = transform.position;
     RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
     return (hit.collider == GetComponent<Collider2D>());
 }
 void OnTriggerEnter2D(Collider2D other)
 {
     if (other.gameObject.CompareTag("Pacdot"))
     {
         other.gameObject.SetActive(false);
         count = count + 10;
         SetCountText();
     }
     // if Pacman collides with "PowerUp" his speed becomes that
     
     //New Code
     if (other.gameObject.CompareTag("PowerUp"))
     {
         StopCoroutine(PowerUp());                //Stops the Coroutine if it had been initiated already
         StartCoroutine(PowerUp());               //Starts the Coroutine 
     }
     
 }
 //The IEnumarator PowerUp() Sets speed to 2 -> Stops execution for 5 seconds(timer) -> Sets speed again to 1
 IEnumerator PowerUp()
 {
     speed = 2f;
     yield return new WaitForSeconds(5f);
     speed = 1f;
 
 }
 //End New Code
 
 //shows the score that you have from the PacDots
 void SetCountText()
 {
     countText.text = "Count: " + count.ToString();
 }

There you go no worries i guess i should had written it that way at first :) anyway i would strongly advise to study about C# and go through all Unity Tutorials, i know it is a bit time consu$$anonymous$$g but trying to start a new project without basic knowledge will be more frustrating on the long run. Cheers can't make it any more clear than that :D

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How would I create a script that spawns objects more frequently as time goes on, then stops after a certain point/amount of time? 1 Answer

How to include speed trigger creation option in this script. 0 Answers

How Do I modify speed to be slower? 2 Answers

system time image effects 0 Answers

How to include speed trigger creation option in this script. 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges