Hey guys,
How can i add force on a ball based on mouse drag. I am trying to build a golf game in 3D, [like this](https://play.google.com/store/apps/details?id=games.onebutton.golfbattle&hl=en_IN) but i am unable to find a way to do it. I am not very good at math so i don't have much idea on vectors. So how can implement this?
This is the best i could come up with and its not working
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallController1 : MonoBehaviour
{
Vector2 startPos, endPos ;
Vector3 direction;
Rigidbody rd2d;
Camera cam;
float angle , magnitude;
private void Start()
{
rd2d = this.GetComponent();
cam = Camera.main;
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
startPos = Input.mousePosition;
Debug.Log(startPos);
}
if (Input.GetButtonUp("Fire1"))
{
endPos = Input.mousePosition;
Debug.Log(endPos);
vdifference.x = endPos.x - startPos.x;
vdifference.z = endPos.y - startPos.y;
vdifference.y = 0;
magnitude = vdifference.magnitude;
ndifference = vdifference.normalized;
angle = Mathf.Tan(ndifference.z / ndifference.x);
// angle = Mathf.Rad2Deg * angle;
Debug.Log("angle " + angle);
Debug.Log("vector " + vdifference);
Vector3 direction = new Vector3(Mathf.Tan(vdifference.z / vdifference.x), 0, 0);
rd2d.AddForce(direction * 10, ForceMode.Impulse);
}
↧