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);
}
}
}
}
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);