Need help with drawing in-game

So… I got this script,

#pragma strict

var mousePos : Vector2;
var dragStart : Vector2;
var prefab : Transform;
var dis : float = 0.15;

function Start () {

}

function FixedUpdate () {

	mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
	
	if(Input.GetKeyDown(KeyCode.Mouse0)) {
	
		dragStart = mousePos;
		Instantiate(prefab,dragStart,Quaternion.Euler(0,90,0));
	
	}
	
	if(Input.GetKey(KeyCode.Mouse0)) { //When dragging...
	
		if(mousePos.x > dragStart.x + dis) { //Right
		
			dragStart = mousePos;
			Instantiate(prefab,dragStart,Quaternion.Euler(0,90,0));
			print('Draw');
			
		}
		
		if(mousePos.x < dragStart.x - dis) { //Left
		
		 	dragStart = mousePos;
		 	Instantiate(prefab,dragStart,Quaternion.Euler(0,90,0));
		 	print('Draw');
		
		}
		
		if(mousePos.y > dragStart.y + dis) { //Up
		
			dragStart = mousePos;
			Instantiate(prefab,dragStart,Quaternion.Euler(0,90,0));
			print('Draw');
			
		}
		
		if(mousePos.y < dragStart.y - dis) { //Down
		
		 	dragStart = mousePos;
		 	Instantiate(prefab,dragStart,Quaternion.Euler(0,90,0));
		 	print('Draw');
		
		}
		
	}

}

And it’s working fine basically. When I move mouse slowly the line is smooth and everything but if I move mouse faster it’s just a complete mess. Any ideas how to fix/improve this?

From here you can download it and see for yourself.

Btw, I also tried to embed the web player to Dropbox but it just gave me error which said that it was unable to load data file…

1 Answer

1

Try to put your code in Update(), FixedUpdate() are used for physics related stuff.

It doesn't really affect at all. The reason I used FixedUpdate is that I read that FixedUpdate is called more often than Update. Like 20 times per frame when Update is called once per frame. So basically it should be smoother when using FixedUpdate.

Another alternative would be increase the number of Instantiate when you move the mouse faster. Besides than mousePos, you can use prevMousePos, you compute the difference between them, the larger the difference the more prefab you will need to Instantiate to fill in the space between your mousePos and prevMousePos.