- Home /
How to make your object follow your touch position faster or instantaneously???
In my 2D game, the object doesn't instantly catch up to where my finger is. Yes, it makes it follow my touch much smoother while moving, but I want it to be instant, I want my 2D object to be instantly on where my finger is...
I also lose control of my object since when it gets late behind following my finger, my finger is no longer touching the collider, and I also want it to be able to only move and follow my finger when I'm touching its collider.
Here's the code I'm using right now. It follows my finger smoothly, but it can't catch up to my touch position to the point where I'm no longer touching its box collider:
if(Physics.Raycast(ray, Mathf.Infinity, playerLayerMask))
{
transform.position = Camera.main.ScreenToWorldPoint
(new Vector3(Input.GetTouch(i).position.x, Input.GetTouch(i).position.y, 9));
}
@kevinspawner Yeah, my object still couldn't catch up to my finger when I'm trying to move it fast.
perhaps using "touches" ins$$anonymous$$d of GetTouch will help: http://docs.unity3d.com/ScriptReference/Input-touches.html
Answer by MaxEden · Feb 11, 2015 at 08:47 AM
Try to do this in LateUpdate()
Another solution is to introduce another variable
Vector3 lastTouch;
void LateUpdate(){
if(Input.touches>0)
{
lastTouch = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(i).position.x, Input.GetTouch(i).position.y, 9));
}
transform.position = lastTouch;
}
Answer by IvovdMarel · Feb 11, 2015 at 07:34 AM
Rather than continuously checking wether or not you are touching the object, you should set a boolean to true, similar to this:
if (Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(ray, Mathf.Infinity, playerLayerMask))
{
dragging = true;
}
}
and then set dragging to false when you release the mouse. (Input.GetMouseButtonUp(0))
While dragging, have the object follow your mouse as you did in your code.
Note - in case you're wondering, this also works for mobile touch.
I've tried that and it still works like my previous code. It gets left behind for some reason when I'm moving my finger too fast.
When you say left behind, you mean it stops following right? Not that it's just slow in following. Does your code look something like this?
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
if(Physics.Raycast(ray, $$anonymous$$athf.Infinity, playerLayer$$anonymous$$ask))
{
dragging = true;
}
}
if (dragging) {
transform.position = Camera.main.ScreenToWorldPoint (new Vector3(Input.GetTouch(i).position.x, Input.GetTouch(i).position.y, 9));
}
Using Get$$anonymous$$ouseButtonDown() for touch input is undocumented and likely unoptimised (and perhaps fragile). $$anonymous$$uch better to use Input.touches for touch input.