- Home /
How can I rotate a shooting-practice target 180 degrees with a timer in C#?
I'm trying to create a shooting range with targets that pop out from the ceiling at random. Preferably, they would rotate sideways from their initial position [UP] (from 0 to 180 degrees) and then back again after spending 4 seconds in the end position [DOWN].
If hit by the 'bullet' or raycast ray, they should return to their initial position and then they will come out again if chosen by the script (which I also need help with).
Any ideas/tips/assistance will be much appreciated.
P.S. I'm quite green when it comes to programming in ALL languages and I'm starting off with C# due to the course I'm taking.
Answer by robertbu · Feb 21, 2014 at 09:18 PM
There are a huge number of ways of implementing this functionality in Unity. One way is to use an AnimationCurve. An animation curve would allow you to give your object a little more life...i.e. it could swing back an forth a bit at the end of its swing so that it felt more real. Attach this script to the object you want to rotate. Note you want the pivot point to be at the bottom of the object. You can accomplish this by putting an empty game object at the bottom of the visible object and making the visible object a child. The script would go on the parent. Here is a sample script. Hit the space bar to cause the object to swing:
#pragma strict
var ac : AnimationCurve;
private var timer = 100.0; // Beyond end of curve
function Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
timer = 0.0;
}
timer += Time.deltaTime / 5.0;
transform.eulerAngles = Vector3(ac.Evaluate(timer)*180.0, 0.0, 0.0);
}
Once you've attached the script, you can click on the animation curve and create a curve to match your object. For example:
A value of 0.0 is rotation 0.0, a value of 1.0 is 180 degrees. The horizontal values go from 0.0 to 1.0. In the script I divide by 5.0, so the whole curve will take 5.0 seconds to execute and be down for approximate 4.0 seconds. Note the wiggle when the graph reaches 1.0. This will cause the object to swing a bit when it first rotates down.