- Home /
Soccer: Control ball curve and projecton
Hello,
I am creating soccer based penalty shoot out game. I have no idea how can i add curve and accuracy factor in ball projection?
I have created simple projection towards goal post by adding force to ball.
Answer by cjdev · Oct 27, 2013 at 03:41 PM
An alternative to using a rigidbody would be to move the transform with a script. If you have a generalized equation you can just define whether the end position results in a goal or not. While there are many ways to get the positions along a curve, I'd personally use Bezier Curves to simulate the trajectory. Basically they're just a curve defined by a start and end point with two control points in the middle. I've recently been using Bezier curves and I use this script for them:
using UnityEngine;
using System.Collections;
// This is a helper class to contain the four points and calculate the cubic function of a Bezier curve
public class Bezier {
public Vector3 A;
public Vector3 B;
public Vector3 C;
public Vector3 D;
float X;
float Y;
float Z;
// The curve is defined by the four points which gives the basis for a cubic approximation
public Bezier(Vector3 point1, Vector3 point2, Vector3 point3, Vector3 point4)
{
A = point1;
B = point2;
C = point3;
D = point4;
}
// Returns the resulting position of the Bezier curve at time t, where 1 >= t >= 0
public Vector3 GetPosition(float t)
{
float n = 1 - t;
X = A.x*n*n*n + 3*B.x*n*n*t + 3*C.x*n*t*t + D.x*t*t*t;
Y = A.y*n*n*n + 3*B.y*n*n*t + 3*C.y*n*t*t + D.y*t*t*t;
Z = A.z*n*n*n + 3*B.z*n*n*t + 3*C.z*n*t*t + D.z*t*t*t;
return new Vector3(X, Y, Z);
}
}
This class will let you get the position at a given percent of the curve. Using the ball as the first point, a point somewhere in front of the ball as the first control point, a point near the target destination as the second control, and finally, a target point, you should be able to get a curve that looks somewhat realistic and still gives you more precise control over the end position. Try playing around with four empty game object's transforms as the points to see what the curve looks like and if it works for you.
Answer by W1k3 · Oct 27, 2013 at 03:25 PM
I'm going to assume you are using instantiate with force to shoot the ball. So lets say force is applied to the Z axis, and you want to curve to the left. You could use rigidbody.AddForce(-2, 0, 0); to apply a small amount of force to left at the same time to give the illusion of curving.
Should i need to make seprate function for curve ball and what about accuracy?