Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class TankController : MonoBehaviour
- {
- private Rigidbody _tankRigidbody;
- private GameObject _barrel;
- private GameObject _turret;
- private GameObject _barrelEnd;
- [SerializeField] private float _movementForce = 10f;
- [SerializeField] private float _turnSpeed = 5f;
- [SerializeField] private float _projectileForce = 10f;
- [SerializeField] private Camera _mainCamera;
- private void Awake()
- {
- _tankRigidbody = gameObject.GetComponent<Rigidbody>();
- _turret = gameObject.transform.GetChild(1).gameObject;
- _barrel = _turret.transform.GetChild(0).gameObject;
- _barrelEnd = _barrel.transform.GetChild(0).gameObject;
- _mainCamera = FindObjectOfType<Camera>();
- }
- // Update is called once per frame
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.Space))
- {
- Fire();
- }
- TurretLookAtMouse();
- }
- private void FixedUpdate()
- {
- if(Input.GetKey(KeyCode.W))
- {
- _tankRigidbody.AddForce(_movementForce * transform.forward);
- }
- if (Input.GetKey(KeyCode.S))
- {
- _tankRigidbody.AddForce(_movementForce * -transform.forward);
- }
- if (Input.GetKey(KeyCode.D))
- {
- transform.Rotate(_turnSpeed * Vector3.up);
- }
- if (Input.GetKey(KeyCode.A))
- {
- transform.Rotate(_turnSpeed * Vector3.down);
- }
- }
- private void TurretLookAtMouse()
- {
- Ray _cameraRay = _mainCamera.ScreenPointToRay(Input.mousePosition);
- Plane _groundPlane = new Plane(Vector3.up, Vector3.zero);
- if (_groundPlane.Raycast(_cameraRay, out float _rayLength))
- {
- Vector3 _pointToLook = _cameraRay.GetPoint(_rayLength);
- Debug.DrawLine(_cameraRay.origin, _pointToLook, Color.blue);
- _turret.transform.LookAt(new Vector3(_pointToLook.x, _turret.transform.position.y, _pointToLook.z));
- }
- }
- private void Fire()
- {
- GameObject bullet = ObjectPool.SharedInstance.GetPooledObject();
- if (bullet != null)
- {
- bullet.transform.position = _barrelEnd.transform.position;
- bullet.transform.rotation = _barrelEnd.transform.rotation;
- bullet.SetActive(true);
- // Change back to bullet.transform.forward, once rotations are sorted out...
- bullet.GetComponent<Rigidbody>().AddForce(bullet.transform.up * _projectileForce, ForceMode.Impulse);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement