For one of my classes that I’m taking, we have to use steering forces to move Hunters and Prey around a map, for the Hunter(s) to chase the nearest prey, and to take into account the bounds of the map (walls) and when nearby, steer away from them. I previously made this assignment work in Flash (it was what was originally assigned), and am trying to convert the project for implementation in Unity (because I love C#, and want to help people [including myself] understand the concepts in a different environment). I’m trying to predict where my hunters/prey are one or more timesteps in the future (the have kinematic rigidbody colliders) using raycasts; I thought it might be logical to do it that way, but I could be wrong (basically trying to a projection of a point by a foward vector akin to a HitTestPoint).
Without getting into “too much” Unity specific things (i.e. leaning on the physics engine to do things versus writing my own code [for practice]), I thought this would work:
protected Vector3 StayOnStage()
{
//Look in front of self - is something there?
RaycastHit hitDetected = new RaycastHit();
if(Physics.Raycast(this.transform.position, forwardVect,out hitDetected, 2f))
{
if(hitDetected.transform.tag =="SideWall"||hitDetected.transform.tag =="VerticalWall")
return Flee(hitDetected.transform.position);
else
return Vector3.zero;
}
else
return Vector3.zero;
}
The returned Vector3 is added to the forward vector in another method, which calculates the final forward vector as a sum of all forces (seeking, fleeing, dodging, etc.). However, I can’t tell why my objects are now flying out of the bounds of the map using this specific code. If it helps, Flee looks like this:
protected Vector3 Flee(Vector3 targetPos)
{
// Set desiredVelocity equal to a vector AWAY from targPos
Vector3 desVel;
Vector3 steeringForce;
desVel = targetPos+transform.position;//subtracting creates a vector TOWARDS the target
// scale desired velocity so its magnitude equals max speed
desVel.Normalize();
desVel *= maxSpeed;
// to get steeringForce subtract current velocity from desired velocity
steeringForce = desVel - velocity;//velocity being an intervariable which is equal to the forward vector * speed
return steeringForce;
}
Any thoughts on what I did wrong? I’ll eventually be going back through to trim out extraneous things (ex. the use of velocity as a variable, probably), but am I approaching this properly using raycasts, or should I be using something else?
Thank you for your time and patience ![]()