Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Character walking to the mouse

Discussion in 'Scripting' started by Sam Shiels, Apr 7, 2008.

  1. Sam Shiels

    Sam Shiels

    Joined:
    Feb 25, 2007
    Posts:
    160
    How can I make a character walk to the mouse position using raycast? The script is the ai script in the fps tutorial.

    Thanks.
     
  2. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    Depends what your needs are. If you need the character to simply walk to the point, ignoring any obstacles which might be in the way, your only trouble is getting the point in 3D space where the mouse was clicked.

    You could for instance use this code in your update:
    Code (csharp):
    1.  
    2.         Ray mouseRay;
    3.         RaycastHit rayHit;
    4.        
    5.         if( Input.GetMouseButtonDown( 0 ) )
    6.         {
    7.             mouseRay = Camera.main.ScreenPointToRay( Input.mousePosition );
    8.        
    9.             if( Physics.Raycast( mouseRay.origin, mouseRay.direction, out rayHit, Mathf.Infinity, groundLayer ) )
    10.             {
    11.                 // Set your character to go to rayHit.point
    12.             }
    13.         }
    14.  
    Where groundLayer is a LayerMask describing the layers which contain your ground objects.

    Otherwise you'll need pathfinding. I'm working on a project to solve exactly this problem:

    http://angryant.com/path.html
     
  3. Sam Shiels

    Sam Shiels

    Joined:
    Feb 25, 2007
    Posts:
    160
    Thanks a lot!