- Home /
Varied force and mouseButtondown help
public class ball_Input : MonoBehaviour {
Ray ry;
public float distanceunits=100;
public GameObject basketBall;
public bool isHit=false;
// Update is called once per frame
RaycastHit hit;
void Update () {
ry = Camera.main.ScreenPointToRay (Input.mousePosition);
//Vector3 positon = ray.GetPoint (distanceunits);
if(Physics.Raycast(ry,out hit,distanceunits))
{
//Debug.Log (hit.transform.gameObject.name);
isHit=true;
}
}
void FixedUpdate()
{
if ((isHit == true)) {//&&(Input.GetMouseButtonDown(0))
basketBall.rigidbody.AddForceAtPosition(new Vector3(0,30,0),hit.transform.position);
isHit = false;
Debug.Log("Clciked");
}
}
}
I have attached this code to my main camera .I am begginer so i am making a simple program where the ball jumps whenever i click it,so far i have succeded in adding a force to the sphere , i cant get it add force only on mouseclick and also i would like to add force that makes the ball go different angles based on the point i click it (z axis not needed) Help
Answer by robertbu · Aug 16, 2014 at 05:47 PM
Here is a bit of rework to your script. For a one-time application of force, you don't need to use FixedUpdate(). Use FixedUpdate() for repeated or continuous application of force. This code assumes that any balls you want to kick have the name 'Ball'. Unless you want to be fancy, generally with a ball if you apply the force towards the center of the ball, the results are expected.
using UnityEngine;
using System.Collections;
public class Ball_Input : MonoBehaviour {
public float distanceunits = 100.0f;
public float hitForce = 500.0f;
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,distanceunits) && hit.transform.name == "Ball") {
var dir = (hit.transform.position - hit.point).normalized;
hit.transform.rigidbody.AddForce (dir * hitForce);
}
}
}
}
Your answer
Follow this Question
Related Questions
How can I add force to a raycast bullet? 2 Answers
AddForceAtPosition Locally Problem. 1 Answer
Add force at position Question 1 Answer
How To Perform A Mouse Click On Game Object 5 Answers
Mouse controlled Laserpointer 1 Answer