Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

[solved]My very first Unity script! (it doesn't do anything)

Discussion in 'Scripting' started by gibberingmouther, Jan 11, 2017.

  1. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    https://hastebin.com/zociyodawu.cs

    it could be because i'm confusing vectors with position coordinates. the MoveTowards method calls for vectors when you would think it would take position coordinates as parameters. i'm just confused and tired, hoping my ducks could help me

    to clarify i'm just trying to add the functionality for moving to a point you left click with the mouse (in 2d). later i will add in the walk animation using Unity's wonderful spriteanimator state machine thingie and then will download and add in some pathfinding so the object goes around rocks and other obstacles on its way. this part shouldn't be really hard ... but i could use some help
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    8,411
    You can definitely save yourself a lot of trial and error by starting here: Learn

    Their exercises take you through in a very logical progression, building upon each new concept steadily.
     
    Ryiah, DroidifyDevs and Kiwasi like this.
  3. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    hi Kurt-Dekker!

    i haven't worked my way through every single tutorial but i did all the ones in the scripting section for beginner and intermediate and did a couple of other ones, including the 2d roguelike project. i read through most of the documentation as well. i also read a very nice little book on C# and did half so far of the project in the back of the book. so while there is still plenty more out there to learn i think i have a pretty decent skills and knowledge base to start my project on.

    the scripting tutorial for coroutines had movement code that i guess i could have tried but i want to know why my code doesn't work so i can learn from it.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    8,411
    That is excellent. There are a couple of things to note about the Vector2.MoveTowards() method and your use the code above that are problematic. See documentation here:

    https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html

    The key step you are missing here is that this method returns a Vector2 that is the "new moved position." You are discarding that result without using it.

    I'm guessing you would want to assign it back to the transform.position of the object you are moving.

    HOWEVER, there's a whole host of other things to keep in mind: Unless you take very specific steps in setting up your camera, the Input.mousePosition field does NOT correspond to the world position of the mouse. Clicking at 100,200 onscreen might make the object go somewhere completely different, and with the default Unity camera setups, this is indeed the case.

    You should review some of the tutorials on setting camera orthogonalSize, or FOV if you are using 3D, and see how those mappings are done. They are generally done with extremely handy methods located on the Camera object itself that help you translate from screen or viewport space into world space and back, in various flavors.
     
    gibberingmouther and Ryiah like this.
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    gibberingmouther likes this.
  6. katoun

    katoun

    Joined:
    Dec 26, 2012
    Posts:
    87
    Code (CSharp):
    1. public class SpriteWalkWithoutPathFinding : MonoBehaviour
    2. {
    3.     [SerializeField]
    4.     float moveSpeed = 10;
    5.  
    6.     Vector3 destination;
    7.  
    8.     void Start()
    9.     {
    10.         destination = transform.localPosition;
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.      
    16.         if (Input.GetMouseButtonDown(0))
    17.         {
    18.             destination = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    19.             destination.z = transform.localPosition.z;
    20.         }
    21.  
    22.         transform.localPosition = Vector3.MoveTowards(transform.localPosition, destination, moveSpeed * Time.deltaTime);
    23.     }
    24. }
    Also make sure the camera projection mode is orthographic.
     
    Last edited: Jan 11, 2017
    Kurt-Dekker and gibberingmouther like this.
  7. katoun

    katoun

    Joined:
    Dec 26, 2012
    Posts:
    87
    You can also use
    Code (CSharp):
    1. transform.localPosition = Vector3.Lerp(transform.localPosition, destination, moveSpeed * Time.deltaTime);
    for a smoother movement.
     
    gibberingmouther likes this.
  8. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    Note that moveSpeed has a significantly different meaning between those two - in the former, it's units/second, in the latter, it's a portion of total distance - any movement will take the same total amount of time, regardless of distance (also, it will never fully reach the destination, just very close, but that's usually not an issue).
     
    Kurt-Dekker and gibberingmouther like this.
  9. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    i tried katoun's code because each line made sense to me, but my sprite still does nothing when i click in the world. i also tried the lerp function, no different.

    i thought it could be my green background which envelopes the camera view but i got rid of that and still no movement. maybe i'll try the method from the coroutines tutorial but i would prefer to figure out what's wrong with this code, which seems like it should work and is nicer than the coroutines code.

    edit: it allowed me to run the program, but Unity says the script can't be loaded. just need to figure out why....
    edit2: i tried resetting the script first (didn't work) then i clicked "remove component". now for some reason the "add component" button can't find my script. it still shows up under "all scripts" and in the assets block.
    edit3: VS is going haywire. it says:
    Assets/spritewalkwithoutpathfinding.cs(5,14): error CS0101: The namespace `global::' already contains a definition for `SpriteWalkNoPathfindingorAnimation'

    edit4: aha! i got it to work! thanks guys. just had to tinker around with Unity and VS
     
    Last edited: Jan 13, 2017
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    8,411
    You probably have not set your camera to orthographic.

    In any case, if you supply the Z depth of the world pos you want, it will work in BOTH camera modes.

    I hacked katoun's script here and this works fine for me, 2D sprite or 3D objects at Z == 0:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SpriteWalkWithoutPathFinding : MonoBehaviour
    5. {
    6.     [SerializeField]
    7.     float moveSpeed = 10;
    8.  
    9.     Vector3 destination;
    10.  
    11.     void Start()
    12.     {
    13.         destination = transform.localPosition;
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         if (Input.GetMouseButtonDown(0))
    19.         {
    20.             // this line takes the mouse position and extends it to a Vector3,
    21.             // supplying as the Z coordinate the "depth into scene" we want.
    22.             Vector3 clickPos = new Vector3( Input.mousePosition.x, Input.mousePosition.y,
    23.                                           transform.position.z - Camera.main.transform.position.z);
    24.             destination = Camera.main.ScreenToWorldPoint(clickPos);
    25.             destination.z = transform.localPosition.z;
    26.         }
    27.      
    28.         transform.localPosition = Vector3.MoveTowards(
    29.             transform.localPosition, destination, moveSpeed * Time.deltaTime);
    30.     }
    31. }
     
  11. gibberingmouther

    gibberingmouther

    Joined:
    Dec 13, 2016
    Posts:
    259
    yeah as i said in edit #4 it works now, it was just some complications involving how VS and Unity work together i think. i'll mark it solved
     
    Kurt-Dekker likes this.
  12. katoun

    katoun

    Joined:
    Dec 26, 2012
    Posts:
    87
    Little by little, you're gonna get the hang of it, but it's very important to follow good examples.
     
    gibberingmouther likes this.
  13. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,502
    I would advise against this usage of Lerp as the object will never fully arrive at it's destination. Third parameter of Lerp is percentage of completion not amount to move.
     
    gibberingmouther likes this.
unityunity