Why can't I get ball movement with this script?
I have been trying to figure out how to add an impulse force on the ball with a button press. I can get movement from the ball with the commented out OnMouseDown() method, but I cannot figure out how to do it otherwise. Here is the code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.Events;
using System.Timers;
public class LaunchBall : MonoBehaviour
{
public Rigidbody rb;
public float forceOnBall;
public float percentage = 0;
public bool buttonPressed = false;
public int sign = 1;
/* void OnMouseDown()
{
GetComponent<Rigidbody>().AddForce(transform.right * 500);
GetComponent<Rigidbody>().useGravity = true;
} */
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void ButtonDown()
{
buttonPressed = true;
}
public void ButtonUp()
{
buttonPressed = false;
}
public void Update()
{
if (buttonPressed)
{
percentage+=sign;
Debug.Log(percentage);
if (percentage == 100 || percentage == 0)
sign *= -1;
}
}
public void HitBall()
{
forceOnBall = percentage * 100;
if (!buttonPressed && percentage > 0)
{
rb.AddForce(0, 0, forceOnBall, ForceMode.Impulse);
}
}
}
Looking at your code you never call the HitBall function anywhere.
Answer by Filhanteraren · Nov 08, 2016 at 03:41 AM
Here is a fixed code that calls the HItBall method:
public class LaunchBall : MonoBehaviour
{
public float force = 1;
private Rigidbody rb;
private float forceOnBall;
private float percentage = 0;
private bool buttonPressed = false;
private int sign = 1;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
public void Update()
{
if (Input.GetButton("Fire1"))
{
percentage += sign;
Debug.Log(percentage);
if (percentage == 100 || percentage == 0)
sign *= -1;
}
if (Input.GetButtonUp("Fire1"))
{
HitBall();
}
}
public void HitBall()
{
forceOnBall = percentage * force;
if (percentage > 0)
{
rb.AddForce(0, 0, forceOnBall, ForceMode.Impulse);
}
}
}
Thanks for your help. I am now looking forward to messing around with the physics of it tomorrow. Is it usually better to code for something like this ins$$anonymous$$d of trying to use the event triggers as I did before? I still don't understand why I couldn't get any movement. It seems like I was close.
I just saw the comment you posted. Whenever I tried to call the HitBall function before, the button and ball would just disappear when I hit play. I may have had it outside of an if statement in the update function.
When using this code, the button disappears when I hit play, then if I click the mouse anywhere on the screen, the button reappears. I was trying to get the percentage to go up when I push the UI Button down, and then shoot the ball when I release the UI Button. With this, I can click the mouse anywhere on the screen and it will increase the percentage and shoot ball upon release.
What UI system are you using to display the button.
The fixed code just checks for any input regardless of any ui
I made the button with create from the hierarchy.