-1

I am trying to make a game object which is basically a ball. For now, I can bring the ball towards the player with the FollowPlayer Script, but cannot rotate towards the player like a ball. Requesting assistance, The code is as of the following:

public float MaxDistance; private Transform Player; public float moveSpeed;

// Start is called before the first frame update
void Start()
{
    Player = GameObject.FindGameObjectWithTag("Player").transform;
    
}

// Update is called once per frame
void Update()
{

    if(Vector3.Distance(Player.transform.position, gameObject.transform.position)<= MaxDistance)
    {
        FollowPlayer();
    }
}

void FollowPlayer()
{
    var lookPos = Player.position - transform.position;
    lookPos.y = 0;
    var rotation = Quaternion.LookRotation(lookPos);

    
    transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Instead of doing this by calculation I would rather make it physics based, use a [Rigidbody](https://docs.unity3d.com/Manual/class-Rigidbody.html) and then e.g. adjust its [angularVelocity](https://docs.unity3d.com/ScriptReference/Rigidbody-angularVelocity.html) thus that it rotates around a vector parallel to the up vector and desired move direction – derHugo Sep 01 '22 at 08:09

1 Answers1

-1

You can use add force in their direction. You can do this or addtorque.

public float speed;
Rigidbody rb;
void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.angularDrag = 5f; //or whatever it needs to be
    rb.drag = 1f; //or whatever it needs to be
}
void Update()
{
    rb.AddForce(transform.forward * speed, ForceMode.Impulse);
}
gbe
  • 1,003
  • 1
  • 7
  • 23
  • Thank you for this, well this does make the enemy look at the player with the direction changing to where the player is, the problem is that when this game object moves towards the player it does not rotate like a ball towards the player when in motion, is there a possible way to make that happen? – Joice Philip Thomas Aug 31 '22 at 15:56
  • @JoicePhilipThomas Just double checking, you want it to move towards the player, while rolling on the ground, like the game slope? – gbe Aug 31 '22 at 22:12
  • @JoicePhilipThomas And **Are you using Rigidbody?** – gbe Aug 31 '22 at 22:21
  • Yes just like a ball when it moves towards the player and yes I am using a Rigid Body on this object, hope this clears. Thanks in advance. – Joice Philip Thomas Sep 01 '22 at 14:27
  • @JoicePhilipThomas in 8 hours I can post a new answer, – gbe Sep 01 '22 at 14:29
  • @JoicePhilipThomas edited my original answer – gbe Sep 01 '22 at 22:16
  • Thankyou for this, could not completely dissolve this, could you please show where to place in the code above. – Joice Philip Thomas Sep 04 '22 at 18:11
  • @JoicePhilipThomas edited again – gbe Sep 04 '22 at 21:41