Reputation: 1
I want to do moving like a MOBA Genre in my game. But i cant solve a problem. My object do one move per click. But i want to do moving all distance by one clicking, how to release this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hero : MonoBehaviour
{
private Vector3 pos = new Vector3(10, 0, 10);
public CharacterController controller;
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 a = transform.position;
Vector3 b = new Vector3(10, 0, 10);
transform.position = Vector3.MoveTowards(a, b, speed);
}
}
}
Upvotes: 0
Views: 555
Reputation: 590
Your code will move the player when the mouse button is down. You need to set the target when the mouse button is pressed and move the player outside the if statement. Here is how you can do it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hero : MonoBehaviour
{
private Vector3 pos = new Vector3(10, 0, 10);
Vector3 a;
Vector3 b;
public CharacterController controller;
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
b = transform.position;// initial value
}
// Update is called once per frame
void Update()
{
a = transform.position;
if (Input.GetMouseButtonDown(0))
{
b = pos;
}
transform.position = Vector3.MoveTowards(a, b, speed);
}
}
Upvotes: 1