Thursday, 19 June 2014

Ball Shooter Script–Unity3D

This blog is becoming more and more Unity3D focused, the XB1 program is so quiet I have not had anything to post about, maybe I should just recycle the ID game releases that are happening….
So, was catching up with events on FaceBook and I spotted a post in a group that I am an admin for, asking if anyone knew how to script shooting a ball, as the code they had written was not working as they expected. So, being the kind of person that likes to help people out, I wrote this.
using UnityEngine;
using System.Collections;

public class BallShooter : MonoBehaviour

    bool mousehold = false;
    bool shoot = false;

    public float PowerBuild = .1f;

    public float MaxVelocity = 2;

    public float power = 0;

    public GameObject ball;
    // Update is called once per frame
    void Update ()
        // Player has clicked the left mouse button...
        if (Input.GetMouseButtonDown(0))
            mousehold = true;
            shoot = false;           

        // Player has released the left mouse button..
        if (Input.GetMouseButtonUp(0))
            if (mousehold)
                shoot = true;

            mousehold = false;

        // While the player has the left mouse button pressed power up the shot..
        if (mousehold && power < 1)
            power += PowerBuild;
            if (power > 1)
                power = 1;

        // Shoot the ball!!!
        if (shoot)
            shoot = false;
            // Get mouse pos in the view.
            Vector3 mp = Camera.main.ScreenToViewportPoint(Input.mousePosition);

            // (.5,.5) is center, so we can elevate and pan the shot angle based on this while creating the velocity.
            Vector3 velocity = new Vector3(MaxVelocity * (mp.x - .5f), MaxVelocity * (mp.y - .5f), MaxVelocity * power);

            // Create the ball.
            GameObject shot = (GameObject)Instantiate(ball, Camera.main.transform.position + Vector3.forward, Quaternion.identity);

            // Give it some velocity.
            shot.rigidbody.velocity = velocity;

            // Reset the power ready for the next shot.
            power = 0;
As you can see, it’s a pretty simple script, check if the player has the left mouse button pressed, if they do then set the hold and shoot variables, if the player releases the left mouse button, then set the shoot flag and un set the mouse hold flag.
While the left mouse button is down, build up power for the shot. Once released, set the shoot flag.
If the shoot flag is set, calculate the velocity, create an instance of the ball and apply the velocity to it, and that’s about it…
If you want to get the whole unity scene, then you can download it off my server here.