- Home /
C# Rotate velocity issue
I have a script which causes a gameobject to move back and forth. It also causes the gameobject to rotate. I'm having a problem where the rotation interferes with the gameobject's velocity. I'm not sure why this happens since when the script starts the gameobject moves normally. Any idea why the rotation and velocity are affecting each other?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Shots_Script : MonoBehaviour
{
public float speed;
public float shotLife;
public float halfShotLife;
// Use this for initialization
void Start (){
GetComponent<Rigidbody2D>().velocity = transform.up * speed;
halfShotLife = shotLife/2;
}
// Update is called once per frame
void Update ()
{
--shotLife;
if(shotLife <= 0){
Destroy(gameObject);
}
transform.Rotate(Vector3.forward * speed);
if(shotLife < halfShotLife){
GetComponent<Rigidbody2D>().velocity = -transform.up * speed;
}
}
}
Answer by smallbit · Jun 17, 2015 at 03:40 AM
You try to modify your transform by two different ways in the same frame, via rigidbody (velocity) and direct access (rotate). Since rigidbody also recalculates gameobject rotation, your attempt of changing it in the same frame causes trouble. I cannot test it now but first solution that comes to my mind is to keep it consistent, i.e. if you change position via rigidbody you should change the rotation via rigidbody torque. Or stick to transforms (translate for moving rotate for rotation).
another solution depends on your setup would be to actually moving your mesh as a child of rigidbody, and rotate it locally without interfering rigidbody calculations (also cannot test but it might work).
Just tried Rigidbody2d.AddTorque and making the rigidbody2d a parent of the gameobject. Neither method worked. Still the same issue of messing with movement.
Dont make rigidbody parent of gameObject, Just move the graphics component as the child and than rotate Only this child (you need reference to that) and not the transform.