Hello hello. I am attempting to create a simple rope-swinging mechanic.
- I shoot a ray out from my FPScontroller camera.
- I return the hit.point data.
- I add a CharacterJoint component to my object and set the anchor point to the hit.point.
Seems simple enough, but I am getting some absolutely bizarre movement. The CharacterJoints centre of gravity seems to be off by a few degrees, and if it reaches certain rotations and positions, or if it hits an object, it completely flips out and shoots off in to infinite - and other such nonsense.
I’ve attached the class below. It is simply attached to a cube with a rigidbody component applied to it.
I’ve tried altering the Swing1Limit.limit as well as Swing2Limit.limit, and while it seems to increase the swing range, it messes with the physics even further.
Should I be using a different joint, or editing some parameters, or something else entirely?
Any and all help is appreciated! Thank you!
using UnityEngine;
using System.Collections;
public class Grapple : MonoBehaviour {
private bool attached;
private CharacterJoint grapple;
private LineRenderer rope;
public Material ropeMaterial;
private RaycastHit hit;
void Start () {
//Create the "rope", assign the rope material, and set the rope width
rope = gameObject.AddComponent<LineRenderer>();
rope.material = ropeMaterial;
rope.SetWidth(0.05F, 0.05F);
}
void Update () {
//If the Grapple has been attached, set the Rope's end-point to the main object's position.
if (attached) {
rope.SetPosition (1, transform.position);
}
//If the left mouse button is clicked
if (Input.GetMouseButtonDown (0)){
//Shoot a ray out from the camera and see if it hits
if(Physics.Raycast (Camera.main.transform.position, Camera.main.transform.forward, out hit)){
//Destroy any previous CharacterJoint
Destroy(grapple);
//Create a new CharacterJoint
grapple = gameObject.AddComponent<CharacterJoint> ();
//Set the Grapple anchor point to where the player clicked
grapple.anchor = hit.point;
//Set the Rope's start point to where the player clicked
rope.SetPosition(0, hit.point);
//Set attached to true
attached = true;
}
}
}
}