why isnt my code working,
I want my arrow to freeze and get stuck to an object upon collision but for some reason my arrow hits an object but then just falls to the ground.
here's my code im using.
using UnityEngine; using System.Collections;
public class bowshooting : MonoBehaviour { public object collision; GameObject prefab; void Start () { prefab = Resources.Load("arrow") as GameObject; }
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
GameObject arrow = Instantiate(prefab) as GameObject;
arrow.transform.position = transform.position + Camera.main.transform.forward;
Rigidbody rb = arrow.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * 20;
arrow.transform.rotation = this.transform.rotation;
}
}
// on collision freeze in place and attach to object
void OnCollisionEnter(Collision collision)
{
this.transform.position = collision.contacts[0].point;
this.GetComponent<Rigidbody>().useGravity = false;
collision.rigidbody.isKinematic = true;
collision.rigidbody.velocity = Vector3.zero;
collision.transform.parent = collision.transform;
collision.transform.localPosition = collision.transform.InverseTransformPoint(collision.contacts[0].point);
collision.rigidbody.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezePositionY;
}
} ,
Answer by UnityCoach · Apr 03, 2017 at 09:11 AM
Well, unless this script is assigned to the arrow itself, OnCollisionEnter will never happen when the arrow hits something, it may be triggered when the bow, or whatever object you assigned it to collides.
You need a script for the bow, and a different script for the arrow.
when I put the OnCollisionEnter part onto the arrow itself it still doesn't freeze the arrow moves around and for some reason makes certain objects disappear. do i need to do something else to the script for it to work?
collision.rigibody is the rigid body you hit. You need to make a reference to the rigid body on the arrow (the same game object) and change its properties.
I would also consider using two colliders, using only one at the tip of the arrow. And using some dot product between the arrow tip and hit surface normals, along with the collision relative speed to validate the arrow gets in.
Answer by Anthonyknowles · Apr 03, 2017 at 09:04 AM
Im a beginner but are you sure you are referencing the arrow here?
this.GetComponent<Rigidbody>().useGravity = false;
might not be getting the actual arrow try using
arrow.GetComponent<Rigidbody>().useGravity = false;
Your answer
Follow this Question
Related Questions
Toggle collider with key 0 Answers
Ignore collision based on position 1 Answer
Objects not colliding 1 Answer
Need help with making a burger mechanic. 0 Answers
How to get contact points between a mesh collider and a line? 1 Answer