- Home /
Sphere rotation in moving direction
Hello!
I am creating a 2D game and I have a "player-shpere" in it. My sphere above the surface (coordinates x = 0, y = 0, z = -1).
And I have a player controller:
void Update()
{
float verticalSpeed = Input.GetAxis("Vertical") * speed;
verticalSpeed *= Time.deltaTime;
float horizontalSpeed = Input.GetAxis("Horizontal") * speed;
horizontalSpeed *= Time.deltaTime;
this.transform.Translate(horizontalSpeed, verticalSpeed, 0);
}
It works fine, but I want my sphere to roll in movig direction (like a real boll is rolling in it's direction). The sphere just have to rotate according "controller" directoin.
What should I do?
Answer by mouurusai · Oct 05, 2014 at 06:37 PM
It's should rotate if you use physics function to move, I think. Anyway you may use something like: using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public float r=0.5f;
public float speed = 3;
void FixedUpdate()
{
float moveDir = Input.GetAxis("Horizontal")*speed*Time.deltaTime;
transform.Translate(moveDir, 0, 0, Space.World);
transform.RotateAround(transform.position, Vector3.forward, -Mathf.Sin(moveDir*r*2*Mathf.PI)*Mathf.Rad2Deg);
}
}
It gives me a very strange result. The sphere rotate very fast and fly somewhere. Anyway, I have updated my question.
transform.Translate(бла-бла ,Space.World) using UnityEngine;
public class NewBehaviourScript : $$anonymous$$onoBehaviour
{
public float r=0.5f;
public float speed = 3;
void FixedUpdate()
{
Vector3 moveDelta = new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, Input.GetAxis("Vertical") * speed * Time.deltaTime);
transform.Translate(moveDelta, Space.World);
Vector3 rotationAxis = Vector3.Cross(moveDelta.normalized, Vector3.up);
transform.RotateAround(transform.position, rotationAxis, -$$anonymous$$athf.Sin(moveDelta.magnitude*r*2*$$anonymous$$athf.PI)*$$anonymous$$athf.Rad2Deg);
}
}
Yes it works! But when I am pressing A or D buttons, sphere starting to roll incorrect (red arrows on picture, it should roll according orange arrow).
It's because you are use axises different from axises in my example.
using UnityEngine;
public class NewBehaviourScript : $$anonymous$$onoBehaviour
{
public float r=0.5f;
public float speed = 3;
void FixedUpdate()
{
Vector3 moveDelta = new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0);
transform.Translate(moveDelta, Space.World);
Vector3 rotationAxis = Vector3.Cross(moveDelta.normalized, Vector3.forward);
transform.RotateAround(transform.position, rotationAxis, $$anonymous$$athf.Sin(moveDelta.magnitude*r*2*$$anonymous$$athf.PI)*$$anonymous$$athf.Rad2Deg);
}
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Make sphere rotate when controlled 7 Answers
click to move workig script!! but pls help with rotation!! :( 1 Answer
2D sprite rotation with velocity and interpolation 1 Answer
Problem in rotation of plane 1 Answer