1. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice
  2. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  3. Unity 2017.2 beta is now available for download.
    Dismiss Notice
  4. Unity 2017.1 is now released.
    Dismiss Notice
  5. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice

Detecting movement (unity 2d)

Discussion in 'Scripting' started by MiikaKokko, Jul 17, 2017 at 12:12 PM.

  1. MiikaKokko

    MiikaKokko

    Joined:
    Mar 19, 2017
    Posts:
    4
    How do i make so my script detects when my player is moving? Please help me! I have tried everything...
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Knight : MonoBehaviour
    5. {
    6.  
    7.     void DetectPlayerMoving()
    8.     {
    9.         //insert code here
    10.     }
    11.  
     
  2. Scabbage

    Scabbage

    Joined:
    Dec 11, 2014
    Posts:
    150
    Erm... is the Knight script attached to a GameObject with a rigidbody? If so all you need to do is get the rigidbody with GetComponent<Rigidbody2D>() in Start and store it in a global variable, then check in FixedUpdate if the magnitude of it's velocity is larger than some threshold.
     
  3. MCrafterzz

    MCrafterzz

    Joined:
    Jun 3, 2017
    Posts:
    56
    If it only moves ones then You could have a moving variable that you enable in your movement code. Then you could set it to false in update if it isn't already code:
    Code (CSharp):
    1.  
    2. bool moving = false;
    3.  
    4. // Add this to movement code:
    5. moving = true
    6.  
    7. void Update() {
    8.         if(moving == true){
    9.                 moving = false;
    10.         }
    11. }
    Hope this helps!