Hello, I’m trying to make an arrow stick into targets, I mainly got it working using raycasting but the arrows are still acting weird. If I shoot straight into the target(currently Unity default cube with rigidbody and an box collider) the arrows usually behave as I want them to (sticking half way in,the right angle), but if I shoot in the corners of the box or at an steep angle the arrows stick in almost whole or even whole and they get rotated a bit. I’m using modified code someone posted in another thread (don’t know where).
Here’s the code attached to the Arrow object:
private var lenght : float;
public var ball : GameObject; //sphere used for debugging
public var slerpOn : boolean = true;
public var slerpMultiplier = 5.0;
function Start() {
lenght = 0.4; //lenght from arrow origin to the arrow tip
slerpOn = true;
}
function FixedUpdate() {
if(rigidbody){
var distanceThisFrame = rigidbody.velocity.magnitude * Time.deltaTime;
}
// If the distance is less than the diameter, just let the physics engine handle collision detection
if (distanceThisFrame > lenght) {
var hit : RaycastHit;
var direction = rigidbody.velocity.normalized;
// If we would hit something this frame, move to that position to ensure it,
// but backed off a bit so we don't go through the collider
if (Physics.Raycast(transform.position, direction, hit, distanceThisFrame)) {
slerpOn = false;
Destroy(rigidbody);
transform.position = hit.point - direction*(lenght/2);
ball.transform.position = hit.point;// moves a ball to the position where the ray hit, the point is always right at the surface where I want it to be, so I can't understand why arrows get randomly offset
transform.parent = hit.rigidbody.transform;
// var joint = gameObject.AddComponent("FixedJoint");
//joint.connectedBody = hit.rigidbody;
}
Debug.DrawLine(transform.position, transform.position + direction * distanceThisFrame);
}
}
function Update() {
if(slerpOn){
transform.right =
Vector3.Slerp(transform.right , rigidbody.velocity.normalized, Time.deltaTime * slerpMultiplier );
}
}
function OnCollisionEnter (collision : Collision) {
slerpOn = false;
}
Also, is there a better way of making the arrow stick than to make it a child of the target and Destroy it’s rigidbody? Tried using a joint but it was very unstable, not working at all.
I am sorry if a question like this has been answered before, I searched the forums, tried to solve this for many hours but now I’m really out of ideas :/. Thank you for help.