mouse position to transform position?

I am making a game where you build armies/bases to destroy your enemies base/army. I am making it so that your army goes to the location clicked on the map. My problem is that Input.mouseposition is the position of the mouse for pixels not an actual position in the game. How do I do this?

my old plan was something like this:

waypoint.transform.position = Input.mouseposition;

3 Answers

3

The mouse position is a point in the screen 2D space, what means an infinite line in the 3D world (a line passing through the camera center and the mouse position).

You should create a ray passing through the mouse position, cast a ray and find the point where it intercepts the map:

function Update(){
  if (Input.GetMouseButtonDown(0)){ // if left button pressed...
    var hit: RaycastHit;
    var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, hit) && hit.transform.name=="Map"){
      // hit.point contains the point where the ray hits the
      // object named "Map"
    }
  }
}

EDITED: The C# version (I hope…):

void Update(){
  if (Input.GetMouseButtonDown(0)){ // if left button pressed...
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit) && hit.transform.name=="Map"){
      // hit.point contains the point where the ray hits the
      // object named "Map"
    }
  }
}

Glad to know that you've got it yourself! Anyway, I edited the answer and posted a C# version to help others (hope it has no errors! C# is so cranky...)

–

You can find quite a few threads about this, if you search around a bit. Here’s one to get you started:

Close

(Input.GetKey(KeyCode.Mouse1)

For C# we usually use this.