Java Code Examples for com.badlogic.gdx.ai.steer.SteeringAcceleration#setZero()

The following examples show how to use com.badlogic.gdx.ai.steer.SteeringAcceleration#setZero() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlendedSteering.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> blendedSteering) {
	// Clear the output to start with
	blendedSteering.setZero();

	// Go through all the behaviors
	int len = list.size;
	for (int i = 0; i < len; i++) {
		BehaviorAndWeight<T> bw = list.get(i);

		// Calculate the behavior's steering
		bw.behavior.calculateSteering(steering);

		// Scale and add the steering to the accumulator
		blendedSteering.mulAdd(steering, bw.weight);
	}

	Limiter actualLimiter = getActualLimiter();

	// Crop the result
	blendedSteering.linear.limit(actualLimiter.getMaxLinearAcceleration());
	if (blendedSteering.angular > actualLimiter.getMaxAngularAcceleration())
		blendedSteering.angular = actualLimiter.getMaxAngularAcceleration();

	return blendedSteering;
}
 
Example 2
Source File: PrioritySteering.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	// We'll need epsilon squared later.
	float epsilonSquared = epsilon * epsilon;

	// Go through the behaviors until one has a large enough acceleration
	int n = behaviors.size;
	selectedBehaviorIndex = -1;
	for (int i = 0; i < n; i++) {
		selectedBehaviorIndex = i;

		SteeringBehavior<T> behavior = behaviors.get(i);

		// Calculate the behavior's steering
		behavior.calculateSteering(steering);

		// If we're above the threshold return the current steering
		if (steering.calculateSquareMagnitude() > epsilonSquared) return steering;
	}

	// If we get here, it means that no behavior had a large enough acceleration,
	// so return the small acceleration from the final behavior or zero if there are
	// no behaviors in the list.
	return n > 0 ? steering : steering.setZero();
}
 
Example 3
Source File: Alignment.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	steering.setZero();

	averageVelocity = steering.linear;

	int neighborCount = proximity.findNeighbors(this);

	if (neighborCount > 0) {
		// Average the accumulated velocities
		averageVelocity.scl(1f / neighborCount);

		// Match the average velocity.
		// Notice that steering.linear and averageVelocity are the same vector here.
		averageVelocity.sub(owner.getLinearVelocity()).limit(getActualLimiter().getMaxLinearAcceleration());
	}

	return steering;
}
 
Example 4
Source File: RaycastObstacleAvoidance.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	T ownerPosition = owner.getPosition();
	float minDistanceSquare = Float.POSITIVE_INFINITY;

	// Get the updated rays
	Ray<T>[] inputRays = rayConfiguration.updateRays();

	// Process rays
	for (int i = 0; i < inputRays.length; i++) {
		// Find the collision with current ray
		boolean collided = raycastCollisionDetector.findCollision(outputCollision, inputRays[i]);

		if (collided) {
			float distanceSquare = ownerPosition.dst2(outputCollision.point);
			if (distanceSquare < minDistanceSquare) {
				minDistanceSquare = distanceSquare;
				// Swap collisions
				Collision<T> tmpCollision = outputCollision;
				outputCollision = minOutputCollision;
				minOutputCollision = tmpCollision;
			}
		}
	}

	// Return zero steering if no collision has occurred
	if (minDistanceSquare == Float.POSITIVE_INFINITY) return steering.setZero();

	// Calculate and seek the target position
	steering.linear.set(minOutputCollision.point)
		.mulAdd(minOutputCollision.normal, owner.getBoundingRadius() + distanceFromBoundary).sub(owner.getPosition()).nor()
		.scl(getActualLimiter().getMaxLinearAcceleration());

	// No angular acceleration
	steering.angular = 0;

	// Output steering acceleration
	return steering;
}
 
Example 5
Source File: CollisionAvoidance.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	shortestTime = Float.POSITIVE_INFINITY;
	firstNeighbor = null;
	firstMinSeparation = 0;
	firstDistance = 0;
	relativePosition = steering.linear;

	// Take into consideration each neighbor to find the most imminent collision.
	int neighborCount = proximity.findNeighbors(this);

	// If we have no target, then return no steering acceleration
	//
	// NOTE: You might think that the condition below always evaluates to true since
	// firstNeighbor has been set to null when entering this method. In fact, we have just
	// executed findNeighbors(this) that has possibly set firstNeighbor to a non null value
	// through the method reportNeighbor defined below.
	if (neighborCount == 0 || firstNeighbor == null) return steering.setZero();

	// If we're going to hit exactly, or if we're already
	// colliding, then do the steering based on current position.
	if (firstMinSeparation <= 0 || firstDistance < owner.getBoundingRadius() + firstNeighbor.getBoundingRadius()) {
		relativePosition.set(firstNeighbor.getPosition()).sub(owner.getPosition());
	} else {
		// Otherwise calculate the future relative position
		relativePosition.set(firstRelativePosition).mulAdd(firstRelativeVelocity, shortestTime);
	}

	// Avoid the target
	// Notice that steerling.linear and relativePosition are the same vector
	relativePosition.nor().scl(-getActualLimiter().getMaxLinearAcceleration());

	// No angular acceleration
	steering.angular = 0f;

	// Output the steering
	return steering;
}
 
Example 6
Source File: Arrive.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
protected SteeringAcceleration<T> arrive (SteeringAcceleration<T> steering, T targetPosition) {
	// Get the direction and distance to the target
	T toTarget = steering.linear.set(targetPosition).sub(owner.getPosition());
	float distance = toTarget.len();

	// Check if we are there, return no steering
	if (distance <= arrivalTolerance) return steering.setZero();

	Limiter actualLimiter = getActualLimiter();
	// Go max speed
	float targetSpeed = actualLimiter.getMaxLinearSpeed();

	// If we are inside the slow down radius calculate a scaled speed
	if (distance <= decelerationRadius) targetSpeed *= distance / decelerationRadius;

	// Target velocity combines speed and direction
	T targetVelocity = toTarget.scl(targetSpeed / distance); // Optimized code for: toTarget.nor().scl(targetSpeed)

	// Acceleration tries to get to the target velocity without exceeding max acceleration
	// Notice that steering.linear and targetVelocity are the same vector
	targetVelocity.sub(owner.getLinearVelocity()).scl(1f / timeToTarget).limit(actualLimiter.getMaxLinearAcceleration());

	// No angular acceleration
	steering.angular = 0f;

	// Output the steering
	return steering;
}
 
Example 7
Source File: Face.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
protected SteeringAcceleration<T> face (SteeringAcceleration<T> steering, T targetPosition) {
	// Get the direction to target
	T toTarget = steering.linear.set(targetPosition).sub(owner.getPosition());

	// Check for a zero direction, and return no steering if so
	if (toTarget.isZero(getActualLimiter().getZeroLinearSpeedThreshold())) return steering.setZero();

	// Calculate the orientation to face the target
	float orientation = owner.vectorToAngle(toTarget);

	// Delegate to ReachOrientation
	return reachOrientation(steering, orientation);
}
 
Example 8
Source File: FollowFlowField.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	// Predictive or non-predictive behavior?
	T location = (predictionTime == 0) ?
	// Use the current position of the owner
	owner.getPosition()
		:
		// Calculate the predicted future position of the owner. We're reusing steering.linear here.
		steering.linear.set(owner.getPosition()).mulAdd(owner.getLinearVelocity(), predictionTime);

	// Retrieve the flow vector at the specified location
	T flowVector = flowField.lookup(location);
	
	// Clear both linear and angular components
	steering.setZero();

	if (flowVector != null && !flowVector.isZero()) {
		Limiter actualLimiter = getActualLimiter();

		// Calculate linear acceleration
		steering.linear.mulAdd(flowVector, actualLimiter.getMaxLinearSpeed()).sub(owner.getLinearVelocity())
			.limit(actualLimiter.getMaxLinearAcceleration());
	}

	// Output steering
	return steering;
}
 
Example 9
Source File: Jump.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
public SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	// Check if we have a trajectory, and create one if not.
	if (target == null) {
		target = calculateTarget();
		callback.reportAchievability(isJumpAchievable);
	}

	// If the trajectory is zero, return no steering acceleration
	if (!isJumpAchievable) return steering.setZero();

	// Check if the owner has reached target position and velocity with acceptable tolerance
	if (owner.getPosition().epsilonEquals(target.getPosition(), takeoffPositionTolerance)) {
		if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "Good position!!!");
		if (owner.getLinearVelocity().epsilonEquals(target.getLinearVelocity(), takeoffVelocityTolerance)) {
			if (DEBUG_ENABLED) GdxAI.getLogger().info("Jump", "Good Velocity!!!");
			isJumpAchievable = false;
			// Perform the jump, and return no steering (the owner is airborne, no need to steer).
			callback.takeoff(maxVerticalVelocity, airborneTime);
			return steering.setZero();
		} else {
			if (DEBUG_ENABLED)
				GdxAI.getLogger().info("Jump",
					"Bad Velocity: Speed diff. = "
						+ planarVelocity.set(target.getLinearVelocity()).sub(owner.getLinearVelocity()).len() + ", diff = ("
						+ planarVelocity + ")");
		}
	}

	// Delegate to MatchVelocity
	return super.calculateRealSteering(steering);
}
 
Example 10
Source File: LookWhereYouAreGoing.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	// Check for a zero direction, and return no steering if so
	if (owner.getLinearVelocity().isZero(getActualLimiter().getZeroLinearSpeedThreshold())) return steering.setZero();

	// Calculate the orientation based on the velocity of the owner
	float orientation = owner.vectorToAngle(owner.getLinearVelocity());

	// Delegate to ReachOrientation
	return reachOrientation(steering, orientation);
}
 
Example 11
Source File: Hide.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	// Initialize member variables used by the callback
	this.distance2ToClosest = Float.POSITIVE_INFINITY;
	this.toObstacle = steering.linear;

	// Find neighbors (the obstacles) using this behavior as callback
	int neighborsCount = proximity.findNeighbors(this);

	// If no suitable obstacles found return no steering otherwise use Arrive on the hiding spot
	return neighborsCount == 0 ? steering.setZero() : arrive(steering, bestHidingSpot);
}
 
Example 12
Source File: ReachOrientation.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
/** Produces a steering that tries to align the owner to the target orientation. This method is called by subclasses that want
 * to align to a certain orientation.
 * @param steering the steering to be calculated.
 * @param targetOrientation the target orientation you want to align to.
 * @return the calculated steering for chaining. */
protected SteeringAcceleration<T> reachOrientation (SteeringAcceleration<T> steering, float targetOrientation) {
	// Get the rotation direction to the target wrapped to the range [-PI, PI]
	float rotation = ArithmeticUtils.wrapAngleAroundZero(targetOrientation - owner.getOrientation());

	// Absolute rotation
	float rotationSize = rotation < 0f ? -rotation : rotation;

	// Check if we are there, return no steering
	if (rotationSize <= alignTolerance) return steering.setZero();

	Limiter actualLimiter = getActualLimiter();

	// Use maximum rotation
	float targetRotation = actualLimiter.getMaxAngularSpeed();

	// If we are inside the slow down radius, then calculate a scaled rotation
	if (rotationSize <= decelerationRadius) targetRotation *= rotationSize / decelerationRadius;

	// The final target rotation combines
	// speed (already in the variable) and direction
	targetRotation *= rotation / rotationSize;

	// Acceleration tries to get to the target rotation
	steering.angular = (targetRotation - owner.getAngularVelocity()) / timeToTarget;

	// Check if the absolute acceleration is too great
	float angularAcceleration = steering.angular < 0f ? -steering.angular : steering.angular;
	if (angularAcceleration > actualLimiter.getMaxAngularAcceleration())
		steering.angular *= actualLimiter.getMaxAngularAcceleration() / angularAcceleration;

	// No linear acceleration
	steering.linear.setZero();

	// Output the steering
	return steering;
}
 
Example 13
Source File: Cohesion.java    From gdx-ai with Apache License 2.0 4 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {

	steering.setZero();

	centerOfMass = steering.linear;

	int neighborCount = proximity.findNeighbors(this);

	if (neighborCount > 0) {

		// The center of mass is the average of the sum of positions
		centerOfMass.scl(1f / neighborCount);

		// Now seek towards that position.
		centerOfMass.sub(owner.getPosition()).nor().scl(getActualLimiter().getMaxLinearAcceleration());
	}

	return steering;
}
 
Example 14
Source File: Separation.java    From gdx-ai with Apache License 2.0 3 votes vote down vote up
@Override
protected SteeringAcceleration<T> calculateRealSteering (SteeringAcceleration<T> steering) {
	steering.setZero();

	linear = steering.linear;

	proximity.findNeighbors(this);

	return steering;
}