1
votes

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.

  1. The ball to only bounce specifically when it is tapped
  2. The ball to bounce in random directions within the screen(forward, left, right)

Here is the code on Unity using c#

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;

    }
}

Video Link: https://youtu.be/XibbUBGdFOc

1
Please edit your question and describe the output in words. Many people will not follow a link to watch a video. - Tom Aranda
Any reason why you are rolling your physics instead of using Unity's? - Micky
@MickyD what do you mean by that can you explain it’s my first time using unity in a serious setting. - Caleb Cimeus
Unity3D has it's own physics built in. There is generally no need to calculate the motion of objects under gravity yourself. Check out the Unity docs; tutorials, particularly the ones on YouTube - Micky
@Andreas W I did as you say and theres an error popping up, - Caleb Cimeus

1 Answers

0
votes

First of all add a tag to your ball (in this case I'll use "ball" as tag)
Then cast a Raycast. With this you'll get if the user clicked on the ball. If he did, then all you'll have to do is to set didBounce to true.

if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0)) {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
        if (hit.transform.tag == "ball") {
            didBounce = true;               
        }
    }
}