Hi,I have checked several other question on this topic already and tried to copy some of the solutions but it doesn’t speed to be working.I can’t tell what i am doing wrong i have tried only adding force when the velocity.Magnitude is below maxspeed that doesn’t work and i have also tried subtracting force/adding force in oppisite direction like in the script below that doesn’t work either
using UnityEngine;
using System.Collections;
public class Wander : MonoBehaviour {
Vector3 targetPosition,direction;
Rigidbody2D rbSelf;
public float changeDirectionTimer,timeBeforeDirectionChange,magnitude;
public LayerMask mask;
public float wanderSpeed,maxSpeed,wanderSpeedLerp;
public bool usingRigidBody;
void Start ()
{
targetPosition = transform.position + new Vector3 (Random.Range (-magnitude,magnitude),Random.Range (-magnitude,magnitude));
rbSelf = GetComponent<Rigidbody2D>();
direction = targetPosition - transform.position;
}
void FixedUpdate ()
{
if(usingRigidBody == true)
{
rbSelf.AddForce(direction* wanderSpeed);
if(rbSelf.velocity.magnitude > maxSpeed)
{
rbSelf.AddForce(-direction * wanderSpeed * 2);
}
}
if(usingRigidBody == false)
{
transform.position = Vector3.MoveTowards(transform.position,targetPosition,wanderSpeedLerp);
}
changeDirectionTimer++;
if(Mathf.RoundToInt( transform.position.x ) == Mathf.RoundToInt( targetPosition.x))
{
if(Mathf.RoundToInt( transform.position.y ) == Mathf.RoundToInt( targetPosition.y))
{
ChangePoisition();
}
}
if(changeDirectionTimer >= Random.Range( timeBeforeDirectionChange - 20 , timeBeforeDirectionChange+ 20))
{
ChangePoisition();
}
Vector3 rayDirection = targetPosition - transform.position;
RaycastHit2D hit = Physics2D.Raycast (transform.position,rayDirection,Vector3.Distance(transform.position,targetPosition) + 0.1f,mask);
Debug.DrawRay(transform.position ,rayDirection ,Color.blue);
Debug.Log (hit.collider.tag);
if(hit.collider.tag == "Walls")
{
ChangePoisition ();
}
}
void ChangePoisition()
{
targetPosition = transform.position + new Vector3 (Random.Range (-magnitude,magnitude),Random.Range (-magnitude,magnitude));
changeDirectionTimer=0;
direction = targetPosition - transform.position;
}
void OnCollisionStay2D()
{
ChangePoisition ();
}
}