- Home /
Ball Bouncing
So I currently drafted up this code to make a simple sprite bounce, now I am a complete begineer when it comes to code and I'd like to understand how to accomplish. Currently the ball bounces on screen tap but I want it to bounce on ball tap, and the ball should bounce in random directions only within the parameters of the screen.
The ball to only bounce specifically when it is tapped
The ball to bounce in random directions within the screen(forward, left, right)
Here is a video Link as to what my code below does: LINK
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBounce : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 gravity;
public Vector3 bounceVelocity;
public float maxSpeed = 5f;
bool didBounce = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0)) {
didBounce = true;
}
}
void FixedUpdate () {
velocity += gravity * Time.deltaTime;
if (didBounce == true) {
didBounce = false;
velocity += bounceVelocity;
}
velocity = Vector3.ClampMagnitude (velocity, maxSpeed);
transform.position += velocity * Time.deltaTime;
}
}
Answer by programer717 · Dec 16, 2017 at 01:10 PM
@cimeuscaleb this is what I use for a ball it also works for cubes I'm not sure about other scripts you can change it how ever you want
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class jump : MonoBehaviour {
public bool onG;
private Rigidbody rb;
void Start () {
rb = GetComponent <Rigidbody> ();
onG = true;
}
void Update () {
if (onG) {
if (Input.GetButtonDown ("Jump")) {
rb.velocity = new Vector3 (0, 5, 0);
onG = false;
}
}
}
void OnCollisionEnter(Collision other){
if (other.gameObject.CompareTag ("ground")) {
onG = true;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612144624im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Not Able to Position Sprite By Pixels 1 Answer
(2D) Rendering only the parts of a sprite that are within specific bounds 3 Answers