- Home /
Question by
SuperCrusher22 · Aug 15, 2021 at 12:00 AM ·
bounce
How to make this happen when object collides with another?
I have a script that I found while searching for a way to make a ball bounce whenever it hits a jump pad. Although this script works for the bouncing, I need a way for it to only bounce when it hits the jump pad. Here is the script:
using UnityEngine;
using System.Collections;
public class bouncer : MonoBehaviour
{
private Rigidbody rb;
private bool enter = false;
private bool exit = false;
public Vector3 Velocity = Vector3.zero;
private Vector3 Gravity = new Vector3(0.0f, -10.0f, .0f);
private float mass = 1.0f;
private Vector3 Impulse = new Vector3(0.0f, 500.0f, 0.0f);
private Vector3 acceleration;
private Vector3 TempVelocity;
public float timeMultipler = 1.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (enter)
{
acceleration = Gravity + Impulse / mass;
enter = false;
}
else
{
acceleration = Gravity;
}
Velocity += acceleration * Time.fixedDeltaTime * timeMultipler;
transform.position += Velocity * Time.fixedDeltaTime * timeMultipler;
}
void OnTriggerEnter()
{
enter = true;
TempVelocity = Velocity; // velocity back up
}
void OnTriggerStay()
{
enter = true;
}
void OnTriggerExit()
{
exit = true;
Velocity = new Vector3(TempVelocity.x, -TempVelocity.y * 0.9899999f, TempVelocity.z); //magic number for perfect bounciness 0.9899999f // you can modify if you need to
}
}
Comment
Answer by The-Peaceful · Aug 15, 2021 at 12:48 PM
Hi @SuperCrusher22 ,
You probably just have to give the jump pads a tag (in the code below: "JumpPad") and then ask if the colliding object has that tag, like so:
void OnTriggerEnter(Collider col)
{
if(col.CompareTag("JumpPad")){
enter = true;
TempVelocity = Velocity; // velocity back up
}
}
void OnTriggerStay(Collider col)
{
if(col.CompareTag("JumpPad")){
enter = true;
}
}
void OnTriggerExit(Collider col)
{
if(col.CompareTag("JumpPad")){
exit = true;
Velocity = new Vector3(TempVelocity.x, -TempVelocity.y * 0.9899999f, TempVelocity.z); //magic number for perfect bounciness 0.9899999f // you can modify if you need to
}
}
Ok. But, whenever I run the script again it bounces whenever the scene loads..