Shn
February 10, 2014, 3:43pm
1
Hi! I’m new to Unity, I’m trying to roll a sphere in all directions. currently i can just move it front and back motion, using the A and D keys respectively. i want to roll the sphere in such a way that,W-front,S-back,A,D-left and right…
please help!
Here is the code
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public float rotationSpeed = 100;
public int jumpHeight = 8;
private bool isFalling = false;
void Update ()
{
//Handle ball rotation.
float rotation = Input.GetAxis("Horizontal")* rotationSpeed;
rotation*= Time.deltaTime;
rigidbody.AddRelativeTorque (Vector3.back * rotation);
if (Input.GetKeyDown (KeyCode.Space) && isFalling == false)
{
Vector3 v = rigidbody.velocity;
v.y = jumpHeight;
rigidbody.velocity = v;
}
isFalling = true;
}
void OnCollisionStay()
{
isFalling = false;
}
}
barjed
February 10, 2014, 5:30pm
2
Your code is only sampling a single input axis - the horizontal one:
float rotation = Input.GetAxis("Horizontal")* rotationSpeed;
You should the same thing for the Vertical axis and combine the two of those in a single Vector3 and use that to calculate the rotation.
In addition you are confusing yourself, because you are actually taking the horizontal axis value (which is usually the X axis) and you multuply it by a Vector3 pointing “back” (0,0,-1)
rigidbody.AddRelativeTorque (Vector3.back * rotation);
This transforms “horizontal” input into a “vertical” one. To fix this, store the input axes values in two floats:
float inputX = Input.GetAxis("Horizontal");
float inputZ = Input.GetAxis("Vertical");
and construct a vector
Vector3 rotatioVector = new Vector3(inputX, 0, inputZ);
And use that to apply the rotation and torque to your spere.
Shn
February 10, 2014, 7:58pm
3
so i did as u asked but
now it only moves back(for both W,S keys)
and left (for both A,D keys)
I think I’m doing something wrong i guess.
here is the code
float rotation1 = Input.GetAxis ("Horizontal") * rotationSpeed;
float rotation2 = Input.GetAxis ("Vertical") * rotationSpeed;
float inputX = Input.GetAxis ("Horizontal");
float inputY = Input.GetAxis ("Vertical");
Vector3 rotationV = new Vector3(inputX, 0, inputY);
rotation1 *= Time.deltaTime;
rotation2 *= Time.deltaTime;
rigidbody.AddRelativeTorque ( rotationV * rotation1);
rigidbody.AddRelativeTorque (rotationV * rotation2);