(スクリプト)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 追加
using UnityEngine.UI;
public class TankMovement2_Velocity : MonoBehaviour
{
public float turnSpeed;
private Rigidbody rb;
private float turnInputValue;
// 追加
public Text velocityLabel;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// 追加
//var vel = rb.velocity.magnitude.ToString("n2");
//velocityLabel.text = "速度:" + vel;
// 改良
var forSpeed = Vector3.Dot(rb.velocity, transform.forward).ToString("n2");
velocityLabel.text = "速度:" + forSpeed;
if (Input.GetKey(KeyCode.LeftShift))
{
rb.velocity += transform.forward * 0.3f;
}
if(Input.GetKey(KeyCode.RightShift))
{
rb.velocity -= transform.forward * 0.2f;
}
TankTurn();
if(Input.GetKeyDown(KeyCode.Z))
{
rb.velocity = Vector3.zero;
}
}
void TankTurn()
{
turnInputValue = Input.GetAxis("Horizontal");
float turn = turnInputValue * turnSpeed * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler(0, turn, 0);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
(実行結果)
- 前進
- 後退