0
\$\begingroup\$

Below is a sample of my current code. It doesn't even move the object at all. I thought I could first get the current forward y rotation of the player and then flip it to get the backward rotation and somehow add a little offset so it's not exactly where the player is, and then make the following object always be at that position. But I don't quite know how to do this.

public Transform player;
public Vector3 offset;
// Start is called before the first frame update
void Start()
{
    Vector3 playerPos = player.transform.position;
}

// Update is called once per frame
void Update()
{
    float targetAngle = player.eulerAngles.y - 180f;
    Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
    transform.position = moveDirection+offset;
}
\$\endgroup\$
1
\$\begingroup\$

Your Vector3 reference to the player position in Start is not being updated, so it will always simply be the player’s original position. But it doesn't appear you are actually even using that reference to update the following transform.

This will do what you are asking for:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SimpleFollow : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Vector3  offset;

    void Update()
    {
        transform.position = player.position + player.TransformDirection(offset);
        transform.rotation = player.rotation;
        
    }
}

Here's an example of how to set this up -- for demo purposes the "Player" is the green Jeep, it will run around a Cinemachine Dolly Track:

Demo Setup

The SimpleFollow component is attached to the red car. In the inspector, the Player Transform is assigned, as well as an offset. In this case, we want the follower to be behind the target, so we give it a negative z value:

SimpleFollow example settings

And Violá:

demo

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.