I have a ball that has an initial burst of force, launching it into the air. This ball would ideally then be able to veer towards its target while continuously losing that starting momentum. It shouldn't gain any velocity when heading towards its target.
Importantly! It can also bounce against walls, this also decreases its momentum.
Unitys built in physics system works great for throwing stuff against walls and seeing it bounce in a very natural manner, I want to keep this but gently push it towards a target.
Most solutions I have found (particually for homing missiles) add a continuous amount of force, which is fine if they are self powered.
In a script before this I would give the ball a force of say... 100 using
ballRigidbody.Addforce(targetDirection, ForceMode.Impulse);
Then I'd like it to be steered using a 'Movement' class.
Below is an example of the ball being pushed by continuously adding force, so its more like a rocket (Not what I'm after!)
public class Movement : MonoBehaviour {
[Header("Get Components")]
[SerializeField]Transform targetTransform_gc;
[SerializeField]Transform ballTransform_gc;
[SerializeField]Rigidbody ballRigidbody_gc;
[Header("Settings")]
public float turnSpeed;
public float ballSpeed;
//Private
private Vector3 targetDirection;
private Quaternion targetRotation;
void Update () {
targetDirection = targetTransform_gc.position -ballRigidbody_gc.position;
targetDirection.Normalize();
targetRotation = Quaternion.LookRotation(ballRigidbody_gc.velocity);
ballTransform_gc.rotation = Quaternion.Slerp (ballTransform_gc.rotation, targetRotation , turnSpeed * Time.deltaTime);
}
void FixedUpdate(){
ballRigidbody_gc.AddForce(targetDirection * ballSpeed);
ballRigidbody_gc.velocity = new Vector3(ballRigidbody_gc.velocity.x, 0, ballRigidbody_gc.velocity.z);
}
}
I'd be really grateful if anyone has some pointers or suggestions.
Thanks very much!
If I understand you correctly, you are looking to change the direction, but not the magnitude of your velocity vector. You can get the current magnitude in 3 dimensions using:
double magnitude = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y,2) + Math.Pow(z, 2));
you can then just multiply a unit vector that points between your ball and the target by this magnitude
Edit
The magnitude of a vector is always computed using the formula I showed below. The magnitude is the total length of the vector, ignoring direction.
A unit vector is just a vector pointing in a given direction, with a magnitude of 1.
At this point you have your magnitude, which is how fast you want to go, and your unit vector, which is what direction you want to go. Multiplying these 2 values together gives you a vector that is both the direction and speed you want to go.