Search Unity

Detecting movement (unity 2d)

Discussion in 'Scripting' started by MiikaKokko, Jul 17, 2017.

  1. MiikaKokko

    MiikaKokko

    Joined:
    Mar 19, 2017
    Posts:
    6
    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:
    268
    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:
    354
    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!