Sprite moves at an angle that is 2x the rotation of the sprite.
I'm a complete newbie and learning 2D game development by trying to make a top-down tank driving game.
Here's my code to control the tank sprite.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TankController : MonoBehaviour
{
// Rigidbody2D rb2D;
public float maxForwardSpeed = 2.0f;
public float maxRotationSpeed = 50.0f;
void Start ()
{
// rb2D = GetComponent<Rigidbody2D>();
}
void Update ()
{
float forwardSpeed = Input.GetAxis("Vertical") * maxForwardSpeed;
float rotationSpeed = Input.GetAxis("Horizontal") * maxRotationSpeed;
transform.Translate(transform.up * forwardSpeed * Time.deltaTime);
transform.Rotate(0, 0, -rotationSpeed * Time.deltaTime);
}
}
It compiles and runs, and the tank forward and back movement is fine but when I rotate the tank to say 45 degrees (Northeast), the actual direction of movement when I press forward is +90 degrees (East). Similarly if I rotate the tank to 90 degrees (East) the actual direction of movement is down (South).
What is going on to cause this behaviour?
I expected the transform.Translate(transform.up * forwardSpeed * Time.deltaTime)
statement to move the tank in the exact direction that the sprite is pointing.
Answer by biletubes · Jul 11, 2017 at 05:23 AM
Well, I got it working by keeping track of the direction using a user-defined variable and then setting position and rotation directly. Not sure why the above method doesn't work or whether this is a good solution. Please comment if there is a problem with this or if you have a better solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TankController : MonoBehaviour
{
//Rigidbody2D rb2D;
public float maxForwardSpeed;
public float maxRotationSpeed;
public float direction;
void Start ()
{
//rb2D = GetComponent<Rigidbody2D>();
direction = 0.0f;
}
void Update ()
{
float forwardSpeed = Input.GetAxis ("Vertical") * maxForwardSpeed;
float rotationSpeed = Input.GetAxis ("Horizontal") * maxRotationSpeed;
direction -= rotationSpeed * Time.deltaTime;
transform.position = transform.position + transform.up * forwardSpeed * Time.deltaTime;
transform.rotation = Quaternion.Euler (0, 0, direction);
}
}