- Home /
How to push away an object raycast c#
Hi i have made my own raycast script . However i don't know how to add force so that the object i hit is pushed away. Can somebody help me with this, all scripts seem to be in javascript.
using UnityEngine;
using System.Collections;
public class RayCaster : MonoBehaviour {
public float strengthOfAttraction = 10.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
float theDistance;
if (Input.GetMouseButton (0)){
Vector3 forward = transform.TransformDirection (Vector3.forward) * 10;
Debug.DrawRay (transform.position, forward, Color.red);
if (Physics.Raycast (transform.position, (forward), out hit)){
theDistance = hit.distance;
print (theDistance + " " + hit.collider.gameObject.name);
}
}
}
}
Vector3 forward = transform.TransformDirection (Vector3.forward) * 10;
is this necessary? Vector3 forward = transform.forward * 10; does the same, I think
Answer by NGC6543 · Dec 27, 2015 at 01:06 AM
maybe Rigidbody.AddForce() / AddRelativeForce() would do that.
if raycast is true, get the Rigidbody Component from the object that is hit and add forces to it.
Answer by maccabbe · Dec 26, 2015 at 04:59 PM
Vector3 force = 1f * Time.deltaTime*transform.forward
hit.rigidbody.AddForce(force);
The hit object should have a rigidbody to use Rigidbody.AddForce
Answer by killerstreak · Dec 28, 2015 at 04:30 PM
You could call the rigidbody of the hit object (provided it has one), then add force to it with the same direction as the raycast has:
dir = raycastdir;
hit.rigidbody.AddForce(dir * force);
PS: mind you that this will shoot the object in a line parallel with the raycast which can be weird if the object isn't struck in the middle or is long and wide, to find a more reasonable addforce direction you could retrieve the normal of the raycasthit, which you can then use as the direction
dir = hit.normal
hit.rigidbody.AddForce(dir * force);
good luck.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
Raycast only works while moving 2 Answers
Selecting an Object 2 Answers