Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to create a bouncy bed

Discussion in 'Scripting' started by Kaperosa, Feb 14, 2018.

  1. Kaperosa

    Kaperosa

    Joined:
    Feb 12, 2018
    Posts:
    12
    I'm trying to make the bed bouncy so when my character goes on it they get an extra boost. I want to add the script to the bed. I tried to do the rb shortcut but for some reason it wasn't working. Does anyone have any ideas on how this can work?

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Trampoline : MonoBehaviour {
    6.     private Animator anim;
    7.     Rigidbody rb;
    8.  
    9.     float bounceAmount = 10;
    10.     bool bounce = false;
    11.     public Transform MyHumanoid;
    12.     void Awake () {
    13.         rb = GetComponent<Rigidbody> ();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update () {
    18.         if(bounce) {
    19.             MyHumanoid.rb.velocity.y = 0;
    20.             MyHumanoid.rb.AddForce(0,bounceAmount,0,ForceMode.Impulse);
    21.             bounce = false;
    22.         }
    23.     }
    24.  
    25.     void OnCollisionEnter (Collision other) {
    26.         if(other.gameObject.name == "MyHumanoid") {
    27.             bounce = true;
    28.  
    29.         }
    30.     }
    31. }
    32.  
    33.  
     
    Last edited: Feb 14, 2018
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    this should be all you need to do

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Trampoline : MonoBehaviour
    5. {
    6.     float bounceAmount = 1000;
    7.  
    8.     void OnCollisionEnter (Collision other)
    9.     {
    10.         if(other.gameObject.name == "MyHumanoid") {
    11.             //bounce = true;
    12.             other.gameObject.GetComponent<Rigidbody>().AddForce(0,bounceAmount,0,ForceMode.Impulse);
    13.         }
    14.     }
    15. }
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    You line 14, is stopping up and down movement. and then you added a very small amount of force, only 10, normally you need something much higher like 500 to 2000.

    you could try addForce() with Mode.VelocityChange to change it's velocity with one update.