In my script, the player hits “s” to rotate 180 degrees. However, if they press “s” again, they rotate 180 degrees again. I don’t want them to be able to rotate again. What am I missing? See script below:
function Update() { if(Input.GetKeyDown("s")) { transform.Rotate(new Vector3(0,1,0),180);} }
I’m guessing the problem is that the player will turn 180˚ each frame.
I also assume that the player is allowed to turn more than once, so say about half a sec after the first turn he can turn again…
If this is the case then the following should work:
var timer : float = 0;
function Update() {
timer += Time.deltaTime;
if(Input.GetKeyDown("s") && timer > 0.5) {
transform.Rotate(new Vector3(0,1,0),180);
timer = 0;
}
}
If you only want the player to be allowed to turn once (and then not again), then you can just use a simple boolean.
e.g.
var ignore : boolean = false;
function Update() {
if(Input.GetKeyDown("s") && ignore == false) {
transform.Rotate(new Vector3(0,1,0),180);
ignore = true;
}
}
you could simply add a check to see what the current rotation is:
var currentRotation = transform.rotation.y;
if(Input.GetKeyDown(“s”) && ignore == false && currentRotation < desiredMaxRotation)
(where desiredMaxRotation is a float)
attach it to the object that should rotate:
var maxRotation : float = 180;
function Start()
{
maxRotation = transform.rotation.y + 180;
}
function Update() {
var currentRotation = transform.rotation.y;
if(Input.GetKeyDown("s") && currentRotation < maxRotation) {
transform.rotation.y = Mathf.Lerp(transform.rotation.y,maxRotation,Time.deltaTime);
}
}
a couple of notes:
this should technically work, assuming your starting rotation y value is less than 180, since if it hits 360 it’ll flip over to zero.
Not really good code overall, but should serve as an example
I think it would be better to just use transform.Rotation and SET the rotation to 180 instead of rotate which well. . . rotate the object every time.