Question by
ultranova0520 · Apr 27 at 03:31 PM ·
unity 2d
Here, you hold space to throw a ball. Longer you hold, more the initial velocity. I want it to go back to 0 everytime i release Space. Any fix?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Throw : MonoBehaviour { [SerializeField] float InitialVelocity; [SerializeField] float Angle; //[SerializeField] LineRenderer _Line; //[SerializeField] float _Step; [SerializeField] Transform _FirePoint; private float angle; private float v0;
private void Update()
{
if (Input.GetKey(KeyCode.Space))
{
//this.angle = Angle * 3;
//v0 = InitialVelocity * -0.5f;
//Debug.Log(angle);
Debug.Log(v0);
Increment();
StopAllCoroutines();
StartCoroutine(Coroutine_Movement());
}
}
IEnumerator Coroutine_Movement()
{
float t = 0; //time
while (t < 100)
{
float x = v0 * t * Mathf.Cos(angle);
float y = v0 * t * Mathf.Sin(angle) - (1f / 2f) * -Physics.gravity.y * Mathf.Pow(t, 2);
transform.position = _FirePoint.position + new Vector3(x, y + 1f, 0);
t += Time.deltaTime;
yield return null;
//v0 = 0;
}
}
private void Increment()
{
if(Input.GetKey(KeyCode.Space))
{
//angle = Angle * Time.deltaTime;
v0 += (InitialVelocity + 0.2f) * Time.deltaTime;
}
}
Comment
Best Answer
Answer by Pathojen · Apr 28 at 09:11 PM
if (Input.GetKeyUp("space"))
{
//Whatever the code
}
now it drops it before throwing it, and then if i hold Space, it increases the velocity, making it go left :). but thanks for the help