Home > Enterprise >  moving objects back and fourth between to points and stopping it on mouse click
moving objects back and fourth between to points and stopping it on mouse click

Time:07-18

Currently trying to move a sprite between two points and making it stop between those two points on mouseclick/tap. Cant figure out how to do that (Script isnt laying on the object that is being moved btw)

 void Update() {
         if(isMoving){
         Vector3 v = startingPos;
         v.x  = distanceToCover * Mathf.Sin(Time.time * triangleSpeed);
         transform.position = v;
         }
         if(Input.GetMouseButtonDown(1)){
             
         }
         
     }

CodePudding user response:

If the first part of the code is working fine then just don't let the move be called meaning just set the isMoving to false.

void Update() {
         if(isMoving){
         Vector3 v = startingPos;
         v.x  = distanceToCover * Mathf.Sin(Time.time * triangleSpeed);
         transform.position = v;
         }
         if(Input.GetMouseButtonDown(1)){
             isMoving = false;
         }  
     }

CodePudding user response:

You could animate that movement and then set speed of animation to 0 when clicked

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class stoponclick : MonoBehaviour
{

public GameObject movingObject;

void Update()
{
if (Input.GetMouseButtonDown(1))
{

        if (movingObject != null)
        {
            if (movingObject.GetComponent<Animator>()!=null)
            {
                movingObject.GetComponent<Animator>().speed=0;
            }
        }
    }
}
}
  • Related