I have a protagonist that can shield itself when the user taps and unshield on release. I want the protagonist to gain health if the user taps at the exact moment a hazard collides with the protaginist.
How should i go about doing this? Thanks in advance.
You can implement this in the OnCollisionEnter function. Something like this:
void OnCollisionEnter(Collision coll) {
if(getTouch() && coll.gameObject.tag == "hazard_object_tag") {
//increase health
}
}
You will have to add it to an existing or a new script on your character. hazard_object_tag is the tag attach to the objects you consider hazardous in the game.
It didn’t work. I used the above code but all its doing is increasing my characters health even if the user taps and holds way before hand. I want it kind of like a rhythm game like guitar hero. You will gain health if you perfectly time your taps.
First of all, if you demand exact timing with the collision, your game would be impossible. So I assume you mean that ‘If user taps close enough compared to time of collision, that increases health’.
So something like this should work:
Introduce some variables in your script:
//Time when user has tapped
private float lastTapTime;
//Time when collision has happened
private float lastCollisionTime;
//This is the time around the collision time
//when tap is accepted
//to be close enough, so in this case
//user can tap 0.05 seconds before or after the collision
private float acceptedTimeFrame = 0.05f;
Then in your OnCollisionEnter just set:
lastCollisionTime = Time.time
And in your Update:
void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
lastTapTime = Time.time;
}
if(Mathf.Abs(lastTapTime-lastCollisionTime)<acceptedTimeFrame)
{
//Increase the health
}
}
You might not want to accept taps which are too close to eachother (so player cant just ‘tap, tap, tap’ all the time), but I think you’ll figure it out how to do it if needed.
I didn’t actually test the code, but the idea at least should be in the right direction.