- Home /
OnMouseDown and OnMouseUp not working,onMouseDown not working
This script is added as a component to the Main Camera (which is parented under the Player GameObject) and should take the positions from OnMouseDown and OnMouseUp to generate a Vector2 that applies a fixed ConstantForce2D to the Player in the selected direction for an amount of time. At first, the script was added to the Player GameObject but OnMouseDown would activate only when you pressed over the Player. I tried adding it to the Main Camera and I tried with and without a BoxCollider but it isn't detecting either OnMouseDown nor OnMouseup. Could somebody help me please?
using UnityEngine;
using System.Collections;
public class DragThrow : MonoBehaviour
{
public Vector2 mouseDown;
public Vector2 mouseUp;
public float max = 2.0f;
bool thrown;
public float speed = 50.0f;
public float delay = 0.3f;
public GameObject player;
void Start()
{
if(player== null)
{
player = GameObject.FindWithTag("Player");
}
}
//classe che salva la posizione sullo schermo quando si clicca col mouse
void OnMouseDown()
{
mouseDown = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
//classe che assegna una forza costante al personaggio tramite un vettore generato da fixedLaunch quando l'utente lascia il mouse
void OnMouseUp()
{
if (!thrown) //verifica che non sia stato lanciato
{
mouseUp = Camera.main.ScreenToViewportPoint(Input.mousePosition);
var force = fixedLaunch(mouseDown - mouseUp);
player.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
player.GetComponent<ConstantForce2D>().force = force * speed;
thrown = true;
StartCoroutine(waiter(delay));
}
}
//classe che attende un dato tempo ed azzera la forza costante e la velocità del corpo per interrompere la spinta
IEnumerator waiter(float n)
{
yield return new WaitForSeconds(n);
player.GetComponent<ConstantForce2D>().force = new Vector2();
player.GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x/10, 0);
thrown = false;
}
//classe che prende un vettore direzione e ne restituisce uno con la stessa direzione e un'intensità costante
Vector2 fixedLaunch(Vector2 dir)
{
var x = 1;
var y = 1;
if (dir.x < 0) //verifica se viene lanciato indietro
{
x = -1;
}
if (dir.y < 0) //verifica se viene lanciato in basso
{
y = -1;
}
var angle = dir.y / dir.x; //calcola coefficiente
if (x < 0 && y < 0) //se dir punta indietro in basso (quindi dividendo le componenti il valore è positivo), rendilo di nuovo negativo
{
angle = -angle;
}
if (angle <= 1 && angle >= -1) //semplice trigonometria
{
return new Vector2(x * max, y * max * Mathf.Abs(angle));
}
return new Vector2(x * max / Mathf.Abs(angle), y * max);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I move the camera to another object in the scene on mouse down? 1 Answer
move the object where camera look 0 Answers