I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast
void Awake()
{
coinRigidBody = coin.GetComponent<Rigidbody>();
}
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
firstTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane);
}
if (touch.phase == TouchPhase.Moved)
{
lastTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane);
}
if (touch.phase == TouchPhase.Ended)
{
Vector3 firstTouchWorldPos = Camera.main.ScreenToWorldPoint(firstTouchPos);
Vector3 lastTouchWorldPos = Camera.main.ScreenToWorldPoint(lastTouchPos);
Vector3 diffWorldPos = lastTouchWorldPos - firstTouchWorldPos;
direction3D = diffWorldPos.normalized;
power = diffWorldPos.magnitude * (force / Time.deltaTime);
Ray firstTouchRay = Camera.main.ScreenPointToRay(firstTouchPos);
Ray lastTouchRay = Camera.main.ScreenPointToRay(lastTouchPos);
RaycastHit hit;
Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction - firstTouchRay.direction, Color.red, 50.0f);
if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction * 100, out hit))
{
Vector3 hitLocation = hit.point;
if (hit.collider.tag == "Coin")
{
projectedVector = Vector3.ProjectOnPlane(direction3D, plane.normal);
coinRigidBody.AddForceAtPosition(projectedVector * power, hitLocation * 5);
throwCoinObject.throwWithForce(power, hitLocation, direction3D);
}
}
}
}
}
The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects. I just want it to hit the first touch origin then move to the direction the swipe was made.
Help would be really appreciated