- Home /
How can I roll a sphere relative to the camera's Y axis but not X axis?
Hello, I've recently started using Unity, and have been using C# as my scripting language of preference. Just as the question says, I'm trying to roll a rigid body sphere in relation to the Y axis of the camera but not the X axis. I have searched both questions and the forums but have been unable to figure this out. The code I'm currently using works well going forward and backward, but unless the camera's X rotation is exactly 0.0f, it causes the sphere to roll offset by the X rotation of the camera. Here is a listing of my current code:
void FixedUpdate () {
if (Input.GetKey ("w"))
rigidbody.AddTorque(Camera.main.transform.right * speed * Time.deltaTime);
if (Input.GetKey ("a"))
rigidbody.AddTorque(Camera.main.transform.forward * speed * Time.deltaTime);
if (Input.GetKey ("s"))
rigidbody.AddTorque(Camera.main.transform.right * -speed * Time.deltaTime);
if (Input.GetKey ("d"))
rigidbody.AddTorque(Camera.main.transform.forward * -speed * Time.deltaTime);
}
I'm sure there's a fairly easy fix for this, but I've been bashing my head on it for a couple hours so I figured I would ask. Thank you in advance!
I'm not exactly sure about your issue.
Which do you need? Is it something else? Respond when you feel like it. Just keep in $$anonymous$$d that if you tell me exactly what you need (a picture might help), I will help you. It's an easy fix, but I need to know what the outcome needs to be.
I'm glad to help you!
Noah.
Thanks for the reply. I have tried to create a diagram of what I'm wanting. I hope it explains the situation better than I can with words. For a little more information, I am using an orbiting camera, which is the reason I do not have a consistent X rotation of the camera.
EDIT: Probably should mention the diagram uses the vertical axis to represent Y, the horizontal axis represents the Z axis, and the unseen depth is the X Axis. The red lines represent the direction of rotation on the X axis.
Answer by whydoidoit · Mar 05, 2014 at 04:30 PM
You want to do this:
var directionToMove = Quaternion.AngleAxis(Camera.main.transform.eulerAngles.y, Vector3.up) * Vector3.forward;
Thank you very much. That works perfectly! I would vote you up, but unfortunately I have no rep yet, but it is exactly what I needed. Thank you so much!
Yup this did it for me. $$anonymous$$y situation, I had a camera moving around a lunar lander and I wanted the torque for different roll/pitch/yaw to be relative to the camera/user's view. Adding this did the trick. $$anonymous$$y code:
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) // left
{
m_Rigidbody.AddTorque(Quaternion.AngleAxis(Camera.main.transform.eulerAngles.y, Vector3.up) * new Vector3(0, 0, 5000 * Time.deltaTime));
}
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.D)) // right
{
m_Rigidbody.AddTorque(Quaternion.AngleAxis(Camera.main.transform.eulerAngles.y, Vector3.up) * new Vector3(0, 0, -5000 * Time.deltaTime));
}