Search Unity

How to move an object to a selected object by clicking?

Discussion in 'Scripting' started by XavLar, Aug 3, 2015.

  1. XavLar

    XavLar

    Joined:
    Feb 14, 2012
    Posts:
    143
    Hi,

    I was recently replaying Spore, and I saw that in the space stage when you have control of the space ship that you can move a "star" or a "planet". I'm having trouble doing this, I have a Click to Move script (from BurgzergArcade's tutorial).

    How do I make my player game object move to the location of the planet game object? via selecting the planet.
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    do you mean this one?

    http://git.burgzergarcade.net/Petey/Click-To-Move/blob/master/Click To Move/Assets/Scripts/PlayerMovement.cs

    lines 53-54 need to be changed.

    the raycast needs to detect the "hitting a planet"

    look at the example for
    http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
    (note you have to provide a distance if you want to use a layermask, they're both numbers and you can't "skip over" an optional parameter when you want to provide an override for another optional parameter later in the paramlist, if you do try the layermask will be implicitly cast to a float and used as the distance :()

    you can then use the RaycastHit to get the transform that is being hit and get a position to move to from that
    http://docs.unity3d.com/ScriptReference/RaycastHit.html
     
    XavLar likes this.