Daniel Lip
Daniel Lip

Reputation: 11343

Why the object never move?

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

public class MoveToSettings : MonoBehaviour
{
    public float speed = 5f;
    public float distanceToMove;

    private bool keepMoving = true;
    private Vector3 startPos;
    private Vector3 endPos;
    private bool moveBack = false;

    private void Start()
    {
        startPos = transform.position;
        endPos = transform.position - transform.right * distanceToMove;
    }

    private void Update()
    {
        if (keepMoving == true && MouseDownEvent.mousedown == true)
        {
            if (transform.position == startPos)
            {
                moveBack = false;
            }

            Vector3.Lerp(startPos, endPos, speed);

            keepMoving = false;
        }
    }
}

It should move to the right to the distanceToMove. distanceToMove in the Inspector is set to 30. But the transform never move.

Even if I'm removing the checking line :

if (keepMoving == true && MouseDownEvent.mousedown == true)

It won't move.

Upvotes: 1

Views: 48

Answers (2)

derHugo
derHugo

Reputation: 90833

speed is a constant value

Lerp interpolates between two positions given a factor of 0 - 1. This makes no sense like you are using it.

What you might rather want to use here is Vector3.MoveTowards

Vector3.MoveTowards(startPos, endPos, speed * Time.deltaTime);

Also see Input.GetMouseButton!


and note that you are calling the entire block only exactly once since you directly reset your keepMoving flag

Upvotes: 2

Ruzihm
Ruzihm

Reputation: 20270

It never moves because you never assign to the transform's position. Vector3.Lerp(startPos, endPos, speed); doesn't change anything by itself. You have to assign the result to something. Also, you should use Vector3.MoveTowards and multiply speed by Time.deltaTime so that lag doesn't affect the speed:

transform.position = Vector3.MoveTowards(startPos, endPos, speed * Time.deltaTime);

Also, you should use Input.GetMouseButton(0) to test for the mouse being clicked:

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

public class MoveToSettings : MonoBehaviour
{
    public float speed = 5f;
    public float distanceToMove;

    private bool keepMoving = true;
    private Vector3 startPos;
    private Vector3 endPos;
    private bool moveBack = false;

    private void Start()
    {
        startPos = transform.position;
        endPos = transform.position - transform.right * distanceToMove;
    }

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {    
            transform.position = Vector3.MoveTowards(startPos, endPos, speed * Time.deltaTime);
        }
    }
}

Upvotes: 2

Related Questions