I have a sphere that I’m trying to move by swiping my finger across the screen, but I’m unable to figure it out. Any thoughts? I can’t get the sphere (called Ball) to move. I’m brand new to Unity, but here’s what I have so far:
using UnityEngine;
using System.Collections;
public class BallMover : MonoBehaviour{
private Vector2 startPos;
private Vector2 endPos;
private Vector2 touchPos;
private Rigidbody rb;
private Touch touch;
void Start(){
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate ()
{
float speed = Time.time;
float moveHorizontal;
float moveVertical;
// Check if user touches screen
if (touch.phase == TouchPhase.Began)
{
// get the x and y coordinates of screen touch
startPos = touch.position;
endPos = touch.position;
// set movement to 0
moveHorizontal = 0.0f;
moveVertical = 0.0f;
}
// Check if user removes finger from screen
if (touch.phase == TouchPhase.Ended)
{
// get last finger touch coordinates
endPos = touch.position;
// record time it took to finish finger swipe
//speed = Time.time - speed;
// set movement to end touch minus begin touch for both x and y axis
moveHorizontal = endPos.x - startPos.x;
moveVertical = endPos.y - startPos.y;
// create movement variable
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
// add force to object
rb.AddForce(movement * speed);
}
}
}
jep7
2
You have declared a variable ‘touch’ and you are dealing with it a lot, but you didn’t define it!
At least you have to add this to your FixedUpdate():
FixedUpdate(){
if(Input.touches.Length > 0){
touch = Input.touches[0];
//put your code inside the FixedUpdate() here
}
}
That did it! You’re a life saver @jep7!!! Thanks!!!