Hello, every time I press the button the ball appears but it doesn’t go to the hoop. Could anyone help me with this problem?
public GameObject player;
public Transform net
public float throwForce;
public bool hasBall;
if (Input.GetKeyUp(KeyCode.O) && hasBall)
{
throwForce = 5;
hasBall = false;
Vector3 A = player.transform.position;
Vector3 B = net.position;
basketball.transform.position = Vector3.MoveTowards(A, B, throwForce * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "ball")
{
hasBall = true;
}
Moving objects in a game is extremely well-traveled ground with many existing solutions ready for you to use off the shelf. Rather than reinventing the wheel I suggest using a free tweening package such as DOTween or LeanTween or iTween.
If you don’t want to use the packages above, at least look at how object movement is handled in one of those packages and adapt your code to suit. It’s not something anyone here is going to retype for you in this little tiny text box.
Assuming your if statement and MoveTowards code are in update, the issue is that GetKeyUp
is called only during the frame that the key is up.
There are 3 Input variations, GetKeyDown, GetKey, and GetKeyUp. Take a look at the documentation
So your issue is that your MoveTowards vector call is only being called for one frame. You want it to happen EVERY frame (After the button is pressed). So you need to separate the code that starts the throwing from the code that moves the ball every frame.
There are a number of ways to accomplish this, but since you appear to be learning I would suggest you create a boolean like isBallMoving
or isAnimating
, and while it is true move the ball toward the net. The trick will be deciding when to stop moving the ball to the net. But I’ll leave it there for you to figure out.
Bottom line, the ball is only changing position on the frame that the key is up. separate your ball moving code from the “throwing trigger” code.
I would also disagree with the notion that you need some tweening package to accomplish this, especially at what appears to be an early learning stage for you. You have already accomplished the tween, you only need to fix how it is called.