- Home /
Add force on the ball based in Mouse Drag
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 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<Rigidbody>();
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);
}
Comment
Your answer
Follow this Question
Related Questions
rigidbody velocity on x axis and addforce on y axis ?? 1 Answer
Multiple Cars not working 1 Answer
Best Way To Handle Multiple Moves (Like Pokemon)? 2 Answers
Distribute terrain in zones 3 Answers
knockback 3d c# 1 Answer