Script for object to follow player at set distance and rotation, 3D
ok so, I'm trying to write a script in which a 3D object follows a short distance behind the player model, and mimics the movement of the player ie jumping and direction facing, and is always attempting to be behind the player. For context, the scene has a fixed third person camera, and the player already has a movement script which has a rotation that matches the direction of movement, and both are rigidbodies. Right now, I've put the same movement script from the player onto the second object so the player's jumps and look direction are mimic'd, but if anything in the scene pushes that object away from the player, or if the player changes direction, obviously it is no longer behind the player.
So my idea was to generate a point directly behind the player, and have the object always attempt to move towards that point. So far I have this code, which pulls the location and rotation from the player's object (character controller) and then attempts to get the inverse rotation (backwards of the player, or as I like to call it, the butt direction), and create a point offset in that direction. Then it puts that point into a SmoothDamp to move the object there.
public class Followtheleader : MonoBehaviour
{
[SerializeField]
private float speed;
public Transform PlayerTransform;
private Vector3 characterOffset;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
void LateUpdate()
{
var LeaderLocation = GameObject.Find("character controller").transform.position;
var LeaderRotation = GameObject.Find("character controller").transform.rotation;
Vector3 characterOffset = new Vector3(0,5,0);
Quaternion.Inverse(LeaderRotation);
float desiredAngle = LeaderRotation.eulerAngles.y;
transform.position = Vector3.SmoothDamp(transform.position, LeaderLocation - (characterOffset * desiredAngle), ref velocity, smoothTime);
}
}
Except its not working at all because I don't actually know what I'm doing. I've been looking at scripts that have the camera follow behind the player, but not really understanding how to apply that stuff correctly. How do I generate that point?? Or, am I even going about this the right way?
Your answer
Follow this Question
Related Questions
My player spins when I enter play mode. What am I missing? 0 Answers
Why won't my model rotate up on X axis? 1 Answer
Rotate character 0 Answers
Copy Rotation in script C# 1 Answer
Make camera rotate around an object while keeping entire area visible 0 Answers