I have an unity 3d game. Within that I have a ball game object on a wooden plank.I have also attached a rigid body to my ball and I am using ScreenToWorldPoint to covert coordinated to world.I am using prospective camera.
My requirement is I want to move my ball on x-axis along with my mouse click by keeping ball y and z coordinates as is. .After clicking mouse ball is moving little bit and after that it is not following my mouse
using UnityEngine;
public class GameManager : MonoBehaviour
{
public Camera mainCamera;
public GameObject ball;
Plane plane = new Plane(Vector3.forward,0);
public Transform target;
public float ballForce;
void Update()
{
Vector3 dir = target.position - ball.transform.position;
Vector3 mousePos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,20.8f));
if (Input.GetMouseButtonDown(0)) {
ball.transform.position = new Vector3(mousePos.x, ball.transform.position.y, ball.transform.position.z);
ball.GetComponent<Animator>().enabled = false;
}
if (Input.GetMouseButtonUp(0))
{
//shoot ball
ball.GetComponent<Rigidbody>().AddForce(dir * ballForce, ForceMode.Impulse);
}
float dist;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out dist))
{
Vector3 point = ray.GetPoint(dist);
target.position = new Vector3(point.x, point.y, 0);
}
}
}
I could not find any errors on console but I can see ball.transform.position is changing only one time with initial click and after that it is not updating the ball position.
Kindly help me as I am a newbie to Unity.,