- Home /
Question by
f1r4tc · Nov 18, 2018 at 11:41 AM ·
gameobjecttouchmove an object
Moving object with finger move
Hi, I'm trying to move a GameObject (which is a sprite) with finger move along the x axis. Here is my code:
using UnityEngine;
public class PlayerController : MonoBehaviour {
private Vector3 previousTouchPosition;
private Vector3 currentTouchPosition;
private void Start()
{
// Store firts touch position on start
previousTouchPosition = Input.GetTouch(0).deltaPosition;
}
private void FixedUpdate()
{
if (Input.touchCount > 0)
{
// Get current touch position
currentTouchPosition = Input.GetTouch(0).deltaPosition;
// Get distance between current touch position and previous one.
float distance = currentTouchPosition.x - previousTouchPosition.x;
// Moving object
transform.position = Vector3.Lerp(transform.position, transform.position + new Vector3(distance, 0.0F, 0.0F), Time.deltaTime);
}
}
}
It's not working perfectly but I want to set a range for my object when moving. I want it to stay within camera view with range (-2,+2)
world units. How am I do that? I mean there will be an if
statement that checks that range but where should I put it?
Comment
Best Answer
Answer by Hellium · Nov 18, 2018 at 11:51 AM
// Moving object
Vector3 destination = transform.position + new Vector3(distance, 0.0F, 0.0F);
destination.x = Mathf.Clamp( destination.x, -2, 2 ) ;
transform.position = Vector3.Lerp(transform.position, destination, Time.deltaTime);
Well, that was easy. Thank you! Should I update the original post?
If the answer fixed your issue, you can simply click on the green check at the left side of the answer.