Reputation: 25
so I am making a 2D character controller where if the mouse is held down(Long click) a player can set a direction of where he wants to fire a projectile, and when the projectile is fired and collided with an object the player can click once(or double click if it's better) to swap the character's position to the projectile's position. I'm trying to do it using Input.onMouseButton and Input.onMouseButtonDown but I can't really figure out. Thank you for everyone that'll help me!
Upvotes: 1
Views: 11137
Reputation: 364
For a long click, you just need to measure the amount to time passed since the first click. Here is an example:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class LongClick : MonoBehaviour
{
public float ClickDuration = 2;
public UnityEvent OnLongClick;
bool clicking = false;
float totalDownTime = 0;
// Update is called once per frame
void Update()
{
// Detect the first click
if (Input.GetMouseButtonDown(0))
{
totalDownTime = 0;
clicking = true;
}
// If a first click detected, and still clicking,
// measure the total click time, and fire an event
// if we exceed the duration specified
if (clicking && Input.GetMouseButton(0))
{
totalDownTime += Time.deltaTime;
if (totalDownTime >= ClickDuration)
{
Debug.Log("Long click");
clicking = false;
OnLongClick.Invoke();
}
}
// If a first click detected, and we release before the
// duraction, do nothing, just cancel the click
if (clicking && Input.GetMouseButtonUp(0))
{
clicking = false;
}
}
}
For a double click, you just need to check whether a second click occurs within a specified (short) interval:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class DoubleClick : MonoBehaviour
{
public float DoubleClickInterval = 0.5f;
public UnityEvent OnDoubleClick;
float secondClickTimeout = -1;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (secondClickTimeout < 0)
{
// This is the first click, calculate the timeout
secondClickTimeout = Time.time + DoubleClickInterval;
}
else
{
// This is the second click, is it within the interval
if (Time.time < secondClickTimeout)
{
Debug.Log("Double click!");
// Invoke the event
OnDoubleClick.Invoke();
// Reset the timeout
secondClickTimeout = -1;
}
}
}
// If we wait too long for a second click, just cancel the double click
if (secondClickTimeout > 0 && Time.time >= secondClickTimeout)
{
secondClickTimeout = -1;
}
}
}
Upvotes: 4
Reputation: 15
Apart from getting the GetMouseButtonDown(int) with the button, you want to track remember to check in which phase it's the button.
Upvotes: 0