- Home /
C#, Unity 2017.2.0f3, Rotating RigidBodyFPS Controller 90 and -90 degrees on button press?
My current code attached to the Player One RigidbodyFPSController in Standard Assets is as follows:
// Update is called once per frame
void Update () {
//rotate the player with Q and E
if (Input.GetKeyDown("q"))
{
transform.Rotate(0, 90, 0);
}
if (Input.GetKeyDown("e"))
{
transform.Rotate(0, -90, 0);
}
}
However, when actually pushing the buttons, the player seems to snap back to how they were facing and not rotating. How do I get it to do what I want?
Input.GetAxis used in the controller is a read only value. It is being read after you have rotated your player and setting the players rotation based on that.
If you want to manipulate the controller you will have to add your own offset value to the value read by GetAxis. eg
// in your code. lets say it's in $$anonymous$$yClass
// use Edit > Project Settings > Script Execution Order if you need to make sure this script runs before FPSController
public static float myYOffset = 0;
private void Update()
{
if (Input.Get$$anonymous$$eyDown("q"))
{
myYOffset += 90;
}
if (Input.Get$$anonymous$$eyDown("e"))
{
myYOffset -= 90;
}
}
.
// in FPSController
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), $$anonymous$$yClass.myYOffset, Input.GetAxis("Vertical"));
I tried your code, and replaced the $$anonymous$$yClass with the name of the script also attached to the object (PlayerOne in my case) and it flags it as "PlayerOne does not exist in the current context" and that targetVelocity cannot directly contain members such as fields or methods.
Well I know my code works. Post both your scripts if you want me to show you how to implement it.
Answer by AlienNova · Oct 21, 2017 at 11:52 PM
I would highly suggest reading https://docs.unity3d.com/ScriptReference/Transform.Rotate.html to fully understand what Rotate() does
The code you're looking for is more along the lines of
if (Input.GetKey(KeyCode.Q))
transform.Rotate (0, 1 * time.DeltaTime * speed, 0);
if (Input.GetKey(KeyCode.E))
transform.Rotate (0, -1 * time.DeltaTime * speed, 0);
Speed is how fast/slow you want it to rotate
Is that formatted right? It's telling me time and speed don't exist in the current context while calling it within void Update () { xxxx }
$$anonymous$$ake sure your declaring speed first. float speed = (Enter number here);
in your class
Thanks, do you know what is causing this red flag now? http://prntscr.com/h1g5or
Your answer

Follow this Question
Related Questions
Rigidbody.AddForce and incorrect rotation 2 Answers
How to have an object inherit rotation of player 1 Answer
How to make a player rotate in a direction with a slope of the ground. 0 Answers
Can i Move/Rotate triggers without Rigidbodies? And other collider questions. 3 Answers
Pysics not working as expected 1 Answer