Hi, I’m just getting into Unity 3D and am trying to develop a simple mini-golf game based on various hacks of code I’ve found. I have a shot script (see below) attached to the main camera of a first person controller prefab. I would like the players position to move to the new position of the ball(prefab) after every shot, but need some help and advice on how to do this,and to know if this is the correct way to go about it.
var startTime : float =0.0;
var elapsedTime : float;
var force : float;
var maxBallForce : float = 2000;
var secondsToMax : float = 5;
var shotTaken : int;
var golfBallPrefab:Transform;
var ball : Transform;
function Awake()
{
ball = Instantiate(golfBallPrefab,transform.position,Quaternion.identity);
}
function Update () {
if(Input.GetButtonDown("Fire1"))
{
startTime =Time.time;
}
if(Input.GetButton("Fire1"))
{
elapsedTime = Time.time - startTime;
force = (maxBallForce / secondsToMax) * elapsedTime;
if(force > maxBallForce)
{
force = maxBallForce;
}
}
if(Input.GetButtonUp("Fire1"))
{
ball.rigidbody.AddForce(transform.forward * force);
shotTaken ++;
}
}
Hi, welcome to the forum!
This script will add a force to the ball in the direction that the camera is pointing, but as it stands, it doesn’t have a way to rotate the camera around the ball. You could probably use Unity’s Mouse Orbit script to get the right behaviour (menu: Component > Camera-Control > Mouse Orbit). However, if you use the ball as the target of this script, the camera will follow the ball as it moves. You could use an empty GameObject at the position of the ball as the target and only move this target after the ball has stopped rolling (use rigidbody.IsSleeping to check for this).
Hi Andeeee, Thanks for the reply, but did you here that big whoosh as something flew over my head? If you have an example script I’d be grateful, else i’ll struggle on and get there in the end :?
I am making a Mini golf game too, and I’m having the same problem you are. I can’t get the club to move to a space that it can hit the ball again when it stops. I’ve tried taking the position of the ball and - 1, but it’s not very reliable.
You can set the camera to a position near the ball with something like the following:-
Camera.main.transform.position = ball.transform.position - Vector3.forward * distance;
Camera.main.transform.LookAt(ball.transform);