- Home /
Question by
Olbaper · Nov 27, 2016 at 08:31 AM ·
2dgameobject2d gameclick to movezone
Zone interactable and no-interactable with an object Unity 2d
Hello everyone! (I'm spanish so excuse my bad english pls) I'm working on a 2d game, my problem is that I have a player, which moves with the mouse(where you click, the object goes right there) but I want to create a zone (a section of te screen) where if you click because you want the object to move there the object doesn't move. In resume, if you click out of the zone, the object does nothing. If someone could help me I'll be so thankful.
This is my code for the moving script:
using UnityEngine;
public class GotoMouse:MonoBehaviour{
public float speed = 1.5f;
private Vector3 target;
public bool canMove = true;
public GotoMouse player;
void Start () {
target = transform.position;
player = FindObjectOfType<GotoMouse> ();
player.canMove = true;
}
void Update () {
if(!canMove)
{
return;
}
if (Input.GetMouseButtonDown (0)) {
target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
target.z = transform.position.z;
player.canMove = true;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
player.canMove = true;
}
}
Comment
Use Raycast2D downward and make it check for notmovable layer gameObject and if the raycast detects a gameObject with the layer notmovable make can move bool to false.
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D ray = Physics2D.Raycast(mousePos, Vector2.down, whaIsNot$$anonymous$$ovable)
if(ray.collider != null){
can$$anonymous$$ove = false;
}else{
can$$anonymous$$ove = true;
}