- Home /
 
Implement moveSpeed to this object script?
How can i implement moveSpeed into this script here? Right now when i click on the enemy, the player justs teleports on him and then falls and i don't want that. I want him to move based on a speed you know move like normal :P
 using UnityEngine;
 using System.Collections;
 
 public class MoveObject : MonoBehaviour {
     
     public Transform target;
     
     void Start() {
         target = GameObject.FindWithTag("Enemy").transform;
     }    
     
     void Update() {
         if(Input.GetMouseButtonUp(0)) {
             transform.position = Vector3.Lerp(transform.position, target.position, Time.time);
         }
     }
 }    
 
              Answer by Statement · Mar 10, 2013 at 04:37 AM
You should increment the position over several frames. One way to do it is to use Vector3.MoveTowards.
 using UnityEngine;
 using System.Collections;
  
 public class MoveObject : MonoBehaviour {     
     public Transform target;
     public float moveSpeed; 
     bool isMoving;
     void Start() {
         target = GameObject.FindWithTag("Enemy").transform;
     }  
  
     void Update() {
        if (Input.GetMouseButtonUp(0))
            isMoving = true;
        if (isMoving && target)
            transform.position = Vector3.MoveTowards(
                                 transform.position, 
                                 target.position, 
                                 moveSpeed * Time.deltaTime);
     }
 }  
 
              Thanks a lot for that :D The funny thing now is that as soon as i hit play it moves on its own before i can click on the enemy :S Also is there a way to make it be active at the same time with my ClickTo$$anonymous$$ove script? I use this one... http://wiki.unity3d.com/index.php/Click_To_$$anonymous$$ove_C
When both are active the player stucks in one place and the whole camera starts shaking :S
Hi, I assumed that since you set target in Start that you hadn't set it in the inspector also... The revised code includes a is$$anonymous$$oving variable that needs to be set before movement occur. 
I have no idea if it will work with that other script. I guess is no, since both of them appear to want to control the object if I understood it correctly. Use one or the other, not both. It's like having two drivers in a car, both fighting for the steering wheel.
Your answer