- Home /
Question by
VenomDestroyr · May 17, 2016 at 04:24 AM ·
c#rigidbodycharacterfixedjoint
RigidBody character wont swing?
I have a grappling hook thing I'm working on but I have run into the problem of my player stopping mid air if I attach it to an object with a fixed joint, the object is supposed to rotate but not move its position, allowing the player to swing on it using physics or in air control but my character just freezes. here is my character script.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class PlayerMovement : MonoBehaviour
{
public float walkSpeed = 10.0f;
public float gravity = 10.0f;
public float maxVelocityChange = 10.0f;
public bool canJump = true;
public float jumpHeight = 2.0f;
private bool grounded = false;
void Awake()
{
GetComponent<Rigidbody>().freezeRotation = true;
GetComponent<Rigidbody>().useGravity = false;
}
void FixedUpdate()
{
if (grounded)
{
// Calculate how fast we should be moving
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= walkSpeed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = GetComponent<Rigidbody>().velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
GetComponent<Rigidbody>().AddForce(velocityChange, ForceMode.VelocityChange);
// Jump
if (canJump && Input.GetButtonDown("Jump"))
{
GetComponent<Rigidbody>().velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
}
}
// We apply gravity manually for more tuning control
GetComponent<Rigidbody>().AddForce(new Vector3(0, -gravity * GetComponent<Rigidbody>().mass, 0));
grounded = false;
}
void OnCollisionStay()
{
grounded = true;
}
float CalculateJumpVerticalSpeed()
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * jumpHeight * gravity);
}
}
and this is the grapple attachment script
using UnityEngine;
using System.Collections;
public class AddJoint : MonoBehaviour {
public GameObject objectBwithFixedJoint;
public GameObject objectA;
// Use this for initialization
void Start () {
GetComponent<Rigidbody>().freezeRotation = false;
GetComponent<Rigidbody>().useGravity = false;
objectBwithFixedJoint = GameObject.FindGameObjectWithTag("Player");
objectA = GameObject.FindGameObjectWithTag("GrappleHook");
FixedJoint fj = objectBwithFixedJoint.AddComponent<FixedJoint>();
fj.connectedBody = objectA.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
}
}
Comment