- Home /
Moving Object to LineRenderer-line
Hey there,
I am making a strategy game for android and I need to guide the player with my finger, drawing a way (way = lineRendererPoints).
When I am done with drawing, the player should follow this way (actually it tracks the points of a lineRenderer), but I don't know how to solve this. The drawing function is already done.
This Script is for the player, but the player is getting immediately at a random position when drawing is done.
var speed : float = 1f;
var points = new Array();
private var drawLiner : DrawLine;
private var mousePressed : int = -1;
var i : int;
function Start(){
drawLiner = GameObject.Find("DrawLine").GetComponent.<DrawLine>();
}
function Update(){
if(drawLiner.isMousePressed){
mousePressed = 1;
}
if(!drawLiner.isMousePressed && mousePressed == 1){
mousePressed = 0;
}
if(mousePressed == 0){
GetPoints();
mousePressed = -1;
}
while(i < points.length){
transform.position = Vector3.MoveTowards(transform.position, points[i], speed * Time.deltaTime);
i++;
}
}
function GetPoints(){
for(var p : int; p < drawLiner.pointsList.Count; p++){
points[p] = drawLiner.pointsList[p];
}
}
Answer by IgorAherne · Dec 27, 2015 at 02:52 PM
Think through your logic :)
while(i < points.length){
transform.position = Vector3.MoveTowards(transform.position, points[i], speed * Time.deltaTime);
i++;
}
This means grab the first destination point, and advance by a small fraction from the current position towards this destination. On the following iteration of while, you grab the next waypoint, advance towards it by a small fraction, repeat.
All of this happens in a single update. The scene is drawn only at the end of the update.
Read about coroutines. This will allow you to advance the player towards a waypoint if a for-loop, (untill he reached it) and then increment i, once you've reached the first point. A coroutine allows you to yield return new WaitForEndOfFrame()
or something like that. So, you can yield every time you advance towards the point by a small fraction.
This will give it a change to be drawn on screen every time we advance by a small amount towards the current point
Your answer
![](https://koobas.hobune.stream/wayback/20220612054021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Error Vector3 does not contain MoveTowards 3 Answers
Edit one element in Vector3 array 1 Answer
Vector3.MoveTowards and Quaternion.RotateTowards 1 Answer
Unexpected behavior on Vector3.moveTowards for Player 0 Answers
Assigning new Mesh Vertices 2 Answers