PhiCato
PhiCato

Reputation: 43

Unity - rigidbody MovePosition slows down reaching the target

I have a problem. I want my enemy to follow the player and try to hit it with the full speed but I cant achieve it. It appears to have faster speed value when its far away and slows down while getting closer to the player. How to make it move at the same speed?

enter image description here

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

public class Dotty : MonoBehaviour
{
    [SerializeField] Transform playerTarget;
    Vector3 direction;
    Rigidbody2D rb;
    float speed = 2.2f;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update()
    {
        direction = playerTarget.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
    }

    private void FixedUpdate() {
        rb.MovePosition(transform.position + direction.normalized * speed);
    }
}

Upvotes: 0

Views: 2359

Answers (1)

Hossein Tari
Hossein Tari

Reputation: 36

first of all change this line :

rb.MovePosition(transform.position + direction.normalized * speed);

to this:

rb.MovePosition(transform.position + direction.normalized * speed * Time.fixedDeltaTime);

and the reason it slows down is probably because the target "Z" position is not "0" (same as player "Z" position).

Upvotes: 2

Related Questions