Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
So I'm making an ai for a tank game but instead of the tank moving smoothly, it just skids around in one direction when it should be moving around the map independently as well. how do I fix this? Here is the code:
C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyTankMove : MonoBehaviour
{
    Rigidbody rbEnemyTank;

    float posX;
    float posZ;


    float posMin = 50f;
    float posMax = 50f;

    Vector3 targetPos;

    public float speedMove = 0.05f;
    public float speedRotate = 0.1f;



    void Awake()
    {
        rbEnemyTank = GetComponent<rigidbody>();
    }

    void Start()
    {
        GetNewPosition();
    }

    void GetNewPosition()
    {
        posX = Random.Range(posMin, posMax);
        posZ = Random.Range(posMin, posMax);

        Vector3 newPosition = new Vector3(posX, transform.position.y, posZ);
        targetPos = newPosition;
    }

    void Update()
    {
        if (Vector3.Distance(transform.position, targetPos) < 10f)
        {
            GetNewPosition();
        }
        Rotate();
    }

    void FixedUpdate()
    {
        Move();
    }

    void Rotate()
    {
        Vector3 tankDir = targetPos - transform.position;
        float step = speedRotate * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(transform.forward, tankDir, step, 0.0f);
    }

    void Move()
    {
        Vector3 moveForward = transform.forward * speedMove;
        rbEnemyTank.MovePosition(rbEnemyTank.position + moveForward);
    }
}


What I have tried:

nothing has worked, I need help but as I'm new to programming please be understanding.

Thanks!
Posted
Updated 1-Feb-21 3:32am
v2

1 solution

When your minimum and maximum are both the same, how do you expect to get any "range"?
float posMin = 50f;
float posMax = 50f;
 
Share this answer
 
Comments
Michael Ciurleo 2-Feb-21 0:41am    
What Should i change it to?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900