Hi everybody !
I’m creating a 2D game and I want that my player move on click. The problem is that, when i click on a UI button, my player is moving and i don’t want that (it is a spaceshooter and the button is the fire button …)
So, this is my Script :
void Update () {
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
I tried to use raycast but my player don’t move…
Some one can help me ?
Thank you, xyHeat
You could try adding a eventsystem and have a plane behind the player and the ui which then registers mouseclicks, I think this should prevent the detecting of clicks when you click on ui elements.
I see that you can use a Event Trigger and in the code use the pointerEventData to get it’s position.
I finally find the good way ! Tjis if the final code :
if (!EventSystem.current.IsPointerOverGameObject())
{
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
me, i did that :
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
if (hit.collider.tag != "Button")
{
target.z = transform.position.z;
}
else
{
return;
}
}
Thank you again ! Bye !