Need help with controlls of a tank

Updated on July 29, 2018 in Unity
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on July 29, 2018

Hello this is my first post here so be nice haha! I have watched brackeys for about 2 months and recently got a new computer than can run unity.

 

I have already made two simple games, PONG and the one where you control a platform that moves back and forward and bounces a ball that destroys platsforms above.

 

Now however I need help with the code of a tank game, down below you will see my code that are the controlls of the tank. ‘Q’ and ‘E’ rotate the barrel of the tank and ‘D’ and ‘A’ rotates the base/body of the tank. Now I want the tank as a whole to move back and forwards if i press ‘W’ and ‘S’, the problem is that the tank just moves up and down from the camera point of view. I want it to move up and down in the direction the body is facing, basically i want it to move like a real tank and not a drifting one or spinning one.

 

 
using UnityEngine;
 
public class Tank : MonoBehaviour {
 
public Rigidbody rb;
public Transform turret;
public Transform body;
public Transform tank;
 
public float turretRotationSpeed = 5f;
public float bodyRotationSpeed = 5f;
public float speed = .2f;
 
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
 
void FixedUpdate()
    {
        if (Input.GetKey(KeyCode.E))
        {
        TurnTurret(1);
        }
    else if (Input.GetKey(KeyCode.Q))
        {
        TurnTurret(-1);
        }
    if (Input.GetKey(KeyCode.D))
        {
        TurnBody(1);
        }
    else if (Input.GetKey(KeyCode.A))
        {
        TurnBody(-1);
        }
    if (Input.GetKey(KeyCode.W))
        {
        moveTank(1f);
        }else if (Input.GetKey(KeyCode.S))
        {
        moveTank(-.5f);
        }
}
 
void moveTank(float x)
        {
        Vector3 move = new Vector3(0, 0, speed * x);
        Quaternion rotation = body.rotation;
        tank.rotation = rotation;
        tank.transform.Translate(move);
        }
void TurnTurret(int x)
        {
        turret.Rotate(0, turretRotationSpeed * x, 0);
        }
void TurnBody(int x)
        {
        body.Rotate(0, bodyRotationSpeed * x, 0);
        }
    }
 

 

I have tries maybe a dussins of ways to make it work but I havn’t found the one that im searching for, in the code above it just spins around, and if i try any other code it just drifts and drives regardless of the way the body is facing.

 

Yes, the code is messy and there are proboaly a thousonds ways to perfect it and not use so many if and ifelse-statements. I just dont know them yet! 😛

 

So if any of you guys know how to “solve” my problem and tidy up my code would be really nice. Hopefully you understand my bad english, not my first language .

  • Liked by
Reply