- Home /
How to implement wind for a projectile motion?
I have already done a projectile using mouse buttons and all. Now everytime i kick a ball there should be a random wind amount so that i kick the ball and the force changes according to the wind. For eg take the pocket tanks game evertime it generates a random wind value. That random wind i can generate through random function but i am not getting how to change the force direction and all.
Here is the script i have used
Rigidbody initialBall = null;
public Rigidbody ball;
Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;
float xAngle, yAngle;
void Start ()
{
SpawnBall();
}
public void SpawnBall()
{
initialBall = (Rigidbody)Instantiate(ball, transform.position + new Vector3(0, 0.3f, 3f), Quaternion.identity);
}
void Update ()
{
if(initialBall)
{
if(Input.GetMouseButtonDown(0))
{
firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
}
if(Input.GetMouseButton(0))
{
secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
currentSwipe.Normalize();
if(currentSwipe.y > 0 )
{
yAngle += currentSwipe.y * 40f;
}
if(currentSwipe.x < 0 )
{
xAngle += currentSwipe.x * 20f;
}
if(currentSwipe.x > 0 )
{
xAngle += currentSwipe.x * 20f;
}
}
if(Input.GetMouseButtonUp(0))
{
if(yAngle> 300)
initialBall.AddForce(xAngle, yAngle, yAngle);
xAngle = 0f;
yAngle = 0f;
}
}
}
Answer by Dave-Carlile · Feb 13, 2013 at 01:39 PM
Wind is just another force, like gravity. It's represented by a vector that points in the wind direction.
A good method to give you a random wind direction and force is Random.insideUnitySphere.
float MaxWindForce = 5;
Vector3 windForce = Random.insideUnitSphere * MaxWindForce;
Then do an AddForce
on your ball each frame (scaling the force by Time.deltaTime
), or use ConstantForce.
initialBall.AddForce(windForce * Time.deltaTime);
Since the force is a vector, you can get the strength of the wind by using the vector magnitude.
float strength = windForce.magnitude;
This will make the ball move according to the wind but i want the trajectory to change according to the wind.
Suppose the ball reaches the max height of the trajectory then at that particular time the trajectory should change according to the wind.
That is not what's happening in that game. Dave Carlisle's answer is what you need. Did you even try it?
yeah i tried it was helpful but thats not what i wanted. The thing is ball is moving with constant force but at some point i want to change the force
But it is an extra force, not the only force. When you want the wind to affect the ball, add the extra force to the ball. So you will have the initial force that propelled it forward and the force of the wind acting upon it.