Objects not Detecting Mouse Clicks Reliably (OnMouseDown())
I have set up the following script to let the player drag objects around my physics-based game. Sometimes it works flawlessly but half of the time it doesn't detect the mouse at all.
The same script is applied to multiple objects and they all have a rigidbody 2d and a box collider 2d, some instances of a preface might work while the other doesn't in the same scene.
I'm using Cinemachine with one virtual orthographic 2d camera.
public float mouseSpeed = 35f;
public float movementSmoothing = 2f;
Vector2 mousePos;
Vector2 mouseStartOffset;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void OnMouseDown()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseStartOffset = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y);
Debug.Log("The Mouse is Down!");
}
void OnMouseDrag()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rb.MovePosition(Vector2.Lerp(rb.position, Vector2.MoveTowards(rb.position, mousePos - mouseStartOffset, mouseSpeed * Time.deltaTime), movementSmoothing));
Debug.Log("Dragging!");
}
Answer by SufianDira · Jul 11, 2020 at 07:05 PM
I tried the following approaches:
1- Deleting all the objects and prefabs and remaking them.
2- Changing the camera and camera settings.
3- Changing the order in layer and z-axis of all objects.
4- Inserting Debug.Log() in the script to make sure the action isn't registered.
What I found out;
1- Objects dragging works fine only after physically interacting with them, i.g. bushing them with another object.
2- By Adding:
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
rb.AddForce(new Vector2(0f, 100f));
}
Dragging will work fine for some time after pressing "A", but it will stop working after around 10 seconds.
But changing the rigid body 2D sleeping mode to "never Sleep" or changing the collision detection to "Continuous" won't fix the issue.
Still looking for a fix ...
Your answer
Follow this Question
Related Questions
Need help with doing something in my game 0 Answers
Event on mouse up 2 Answers
Detect mouse press and release 3 Answers