- Home /
How to have an object moving to one direction and rotate it whitous affecting the direction
public class Ship_Movement : MonoBehaviour {
public float ShipSpeed = 0;
public float RotateSpeed = 280;
Transform myT;
Quaternion targetRotation;
public float v3x;
public float v3z;
public float maxY = 150;
private void Start()
{
targetRotation = myT.rotation;
}
private void Awake()
{
myT = transform;
}
// Update is called once per frame
void Update ()
{
v3x = myT.position.x;
v3z = myT.position.z;
if (v3x < -330 | v3x > 330)
{
v3x = v3x * -1;
Vector3 position = Vector3.one;
position.x = v3x;
position.z = v3z;
myT.localPosition = position;
}
if (v3z < -150 | v3z > 150)
{
v3z = v3z * -1;
Vector3 position = Vector3.one;
position.z = v3z;
position.x = v3x;
myT.localPosition = position;
}
if (ShipSpeed > 0)
{
Speed();
myT.position += (myT.forward * ShipSpeed * Time.deltaTime / 2);
ShipSpeed -= 1;
}
else
{
ShipSpeed = 0;
Speed();
}
targetRotation *= Quaternion.AngleAxis(RotateSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, Vector3.up);
myT.rotation = targetRotation;
}
void Speed()
{
if (Input.GetAxis("Vertical") > 0 && ShipSpeed<=495)
{
ShipSpeed += 5;
}
}
}
Comment
Answer by Piyush_Pandey · May 15, 2017 at 07:52 AM
In your code
myT.position += (myT.forward * ShipSpeed * Time.deltaTime / 2);
this will get hampered if you change the orientation of your object. You must create and empty parent. Give this parent the change in positions. Make the space ship as child of it. Now rotate it in the way you want.
Transform translate_transform , rotate_transform;
private void Awake()
{
translate_transform = transform;
rotate_transform = translate_transform.FindChild("spaceship");//name of the child to rotate
}
// Update is called once per frame
void Update ()
{
v3x = myT.position.x;
v3z = myT.position.z;
if (v3x < -330 | v3x > 330)
{
v3x = v3x * -1;
Vector3 position = Vector3.one;
position.x = v3x;
position.z = v3z;
myT.localPosition = position;
}
if (v3z < -150 | v3z > 150)
{
v3z = v3z * -1;
Vector3 position = Vector3.one;
position.z = v3z;
position.x = v3x;
myT.localPosition = position;
}
if (ShipSpeed > 0)
{
Speed();
translate_transform.position += (translate_transform.forward * ShipSpeed * Time.deltaTime / 2);
ShipSpeed -= 1;
}
else
{
ShipSpeed = 0;
Speed();
}
targetRotation *= Quaternion.AngleAxis(RotateSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, Vector3.up);
rotate_transform.rotation = targetRotation;
}
void Speed()
{
if (Input.GetAxis("Vertical") > 0 && ShipSpeed<=495)
{
ShipSpeed += 5;
}
}
Your answer
Follow this Question
Related Questions
getting the direction of object 1 Answer
Objects Rotation to modify Objects transform velocity/Direction of travel 1 Answer
How do I rotate a circle of objects so that a specific object is in front of the camera? 2 Answers
rotation of the object to a given angle 1 Answer
Make object appear within camera view 0 Answers