- Home /
Question by
melvincostner · Jul 02, 2021 at 03:12 PM ·
arraytransform.positionmousepositionmouseclick
save and move to mouse click positions
Hello, I'm trying to get the position of the mouse click, and store it in an array and then make the object go through all the stored positions.
the idea is after the maximum number is stored it moves to the positions
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouse : MonoBehaviour
{
public float speed;
public Camera mainCamera;
public Vector3[] wayPoints;
private Vector3 mouseWorldPos;
private int index;
public GameObject myObject;
private void Update()
{
MousePosition();
AddPoint();
}
void MousePosition()
{
mouseWorldPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPos.z = 0;
transform.position = mouseWorldPos;
}
private void AddPoint()
{
if (Input.GetMouseButtonDown(0))
{
if (index < wayPoints.Length)
{
wayPoints[index] = mouseWorldPos;
index++;
Move();
}
}
}
void Move()
{
myObject.transform.position = Vector2.MoveTowards(transform.position, wayPoints[index], speed * Time.deltaTime);
}
}
Comment
Answer by kskjadav007 · Jul 06, 2021 at 12:39 PM
Try This
public class BasePartation : MonoBehaviour { public float speed;
public Camera mainCamera;
public List<Vector3> wayPoints;
private Vector3 mouseWorldPos;
private int index;
public GameObject myObject;
private void Update()
{
AddPoint();
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(Move());
}
}
private void AddPoint()
{
if (Input.GetMouseButtonDown(0))
{
mouseWorldPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPos.z = 0;
wayPoints.Add(mouseWorldPos);
}
}
IEnumerator Move()
{
while (myObject.transform.position != wayPoints[index])
{
myObject.transform.position = Vector3.MoveTowards(myObject.transform.position, wayPoints[index], 2f * Time.deltaTime);
yield return null;
}
}
}