- Home /
 
               Question by 
               GoonLvOver9000 · Feb 23 at 12:40 AM · 
                movementmouseposition  
              
 
              How Do I Make An Object Move In A Set Direction Continuously?
I am moving a player object around an arena with mouse clicks, but the object stops when it gets to the position the mouse was clicked at. How can I make it continue moving even after that? What I am looking for is a "move in the direction of X position" Here's my code:
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EzrealCode : MonoBehaviour
 {
     [SerializeField] float heartPoints = 6.00f;
     [SerializeField] float manaPoints = 8.00f;
 
     [SerializeField] float speed = 5f;
 
     Vector2 lastClickedPos;
     bool moving;
 
     private void Update()
     {
         
 
         if (Input.GetMouseButtonDown(0))
         {
             lastClickedPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
             moving = true;
         }
 
         if (moving && (Vector2)transform.position != lastClickedPos)
         {
             float step = speed * Time.deltaTime;
             transform.position = Vector2.MoveTowards(transform.position, lastClickedPos, step);
         }
 
         else
         {
             moving = false;
         }
     }
 }
 
               Comment
              
 
               
              Answer by Master109 · Feb 23 at 01:46 AM
 using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class EzrealCode : MonoBehaviour
  {
      [SerializeField] float heartPoints = 6.00f;
      [SerializeField] float manaPoints = 8.00f;
  
      [SerializeField] float speed = 5f;
  
      Vector2 lastClickedPos;
      Vector2 moveDirection;
      bool moving;
  
      private void Update()
      {
          
  
          if (Input.GetMouseButtonDown(0))
          {
              lastClickedPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
              moveDirection = lastClickedPos - (Vector2) transform.position;
              moving = true;
          }
  
          if (moving && (Vector2)transform.position != lastClickedPos)
          {
              float step = speed * Time.deltaTime;
              transform.position += (Vector3) moveDirection.normalized * step;
          }
  
         //  else
         //  {
         //      moving = false;
         //  }
      }
  }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                