I’ve been using these forums for about a year now, and I’ve been able to find an answer to every problem I’ve come across until now.
I’m trying to get a player rigidbody to move relative to a vehicle’s rigidbody when you stand on it, I’ve tried using a transform and simply parenting it and the result just doesn’t have the bouncy realism that a rigid body does.
Here’s the code for my player, where I think about it in terms of magnetic boots, which pull you towards the vehicle and slowly match your speed to it.
The really juicy problem here is, how to addforce relative to another object’s velocity.
Any help is appreciated.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour {
public Rigidbody rb;
public Rigidbody vehicleRb;
public Camera cam;
public float speed;
public Vector3 speedLimit;
public float magBootRange = 0.5f;
void Start () {
rb = GetComponent<Rigidbody>();
cam = transform.GetComponentInChildren<Camera>();
}
void FixedUpdate () {
RaycastHit hit;
Ray downRay = new Ray(transform.position, -Vector3.up);
if (Physics.Raycast(downRay, out hit)) {
if(hit.transform.tag == "Vehicle") {
if(hit.distance <= magBootRange) {
colRB = hit.rigidbody;
Move(colRB.velocity + speedLimit);
}
else {
colRB = null;
}
}
else {
Move(speedLimit);
colRB = null;
}
}
}
void Move(Vector3 maxVelocity) {
print(rb.velocity + " of " + maxVelocity);
if(Mathf.Abs(rb.velocity.x) < maxVelocity.x && Mathf.Abs(rb.velocity.y) < maxVelocity.y && Mathf.Abs(rb.velocity.z) < maxVelocity.z) {
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 desiredMove = cam.transform.forward*moveVertical + cam.transform.right*moveHorizontal;
rb.AddForce(desiredMove * force);
}
}
}