OnTriggerEnter and UI button
Hi. I'm currently working on something and I need help. I'm making a football game and I'm trying to add kick button.I already wrote the script for kicking the ball but it automatically kicks it when I get near it. Can anyone change my script? I want it to be something like : when player enters trigger(ball) AND if he presses the UI button, then something happens. Is it possible to add it to if function using "&&"? Thank you.
public class kick : MonoBehaviour
{
private float kickForce = 3;
public GameObject ball;
private void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "player") //could "&&" be added here?
{
Vector3 direction = (other.transform.position - transform.position).normalized;
ball.GetComponent<Rigidbody>().AddForce(-direction * kickForce, ForceMode.Impulse);
}
}
}
Answer by Hellium · Nov 14, 2019 at 08:51 AM
public class kick : MonoBehaviour
{
private float kickForce = 3;
public GameObject ball;
private bool canKick;
// Call this function in the OnClick event of the UI button
public void TryKick()
{
if (canKick)
{
Vector3 direction = (other.transform.position - transform.position).normalized;
ball.GetComponent<Rigidbody>().AddForce(-direction * kickForce, ForceMode.Impulse);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.transform.CompareTag("player")
canKick = true;
}
private void OnTriggerExit(Collider other)
{
if (other.transform.CompareTag("player")
canKick = false;
}
}
can you tell me what type of collieder you are using i mean sphere or box
Answer by dacarrera · Nov 14, 2019 at 01:32 AM
I think you have a good start and you're thinking about the problem in a good way. However, for what you want to do, OnTriggerEnter()
isn't the best approach. It's functionality is only called when the Collider enters the trigger boundary, not every frame while it's inside. So you'd actually want to check if your player is in range (rather than just entering a trigger once). You have different options and should think about what would be best for your game:
There's an
OnTriggerStay()
docs ref that is called just about every frame that the collider is touching the trigger.You could just check if the player is in range by comparing transform.positions.
It really just depends how you have your scripts setup/organized. If you have an actual "kick" button then you don't need to be always checking for range since you can just check when "kick" is called. If you want your Kick button to become available when the player is in range, that's when OnTriggerEnter()
can become an option, since you can make the Kick button visible once the player is in range. Just try to thinking about the step-by-step that happens during your game and it'll help you figure out what is consistent with how your game is being made^^
Thank you so much for the answer and for the tips! I really appreciate your help