之前学的是建模,用C#编写游戏刚入门,也有很多小错误,和最开始写c是一样的,很多看着书都能敲错,所以把小错误记
下来。
1.对坦克进行上下左右控制。应该写成Tank结果把名字小写了,导致很长时间没看出来
void Start()
{
target = GameObject.Find("Tank");
}
2.在写完程序后一定要先运行,先在VS中运行了,才能在unity中实现相应操作
3.控制坦克的移动这段程序我们要把C#托在Tank上才能实现
控制炮管、炮塔:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Tank : MonoBehaviour
{
public Transform turret;
public Transform gun;
private float turretRotSpeed = 0.5f;
private float turretRotTarget = 0;
private float maxRoll = 10f;
private float minRoll = -4f;
private float turretRollTarget = 0;
void Start()
{
turret = transform.FindChild("turret");
gun = turret.FindChild("gun");
}
private void Update()
{
float steer = 20;
float x = Input.GetAxis("Horizontal");
transform.Rotate(0, x * steer * Time.deltaTime, 0);
float speed = 3f;
float y = Input.GetAxis("Vertical");
Vector3 s = y * transform.forward * speed * Time.deltaTime;
transform.transform.position += s;
TurretRotation();
turretRotTarget = Camera.main.transform.eulerAngles.y;
turretRollTarget = Camera.main.transform.eulerAngles.x;
TurretRoll();
}
//炮塔旋转
public void TurretRotation()
{
if (Camera.main == null)
return;
if (turret == null)
return;
//归一化角度
float angle = turret.eulerAngles.y - turretRotTarget;
if (angle < 0) angle += 360;
if (angle > turretRotSpeed && angle < 180)
turret.Rotate(0f, -turretRotSpeed, 0f);
else if (angle > 180 && angle < 360 - turretRotSpeed)
turret.Rotate(0f, turretRotSpeed, 0f);
}
public void TurretRoll()
{
if (Camera.main == null)
return;
if (turret == null)
return;
//获取角度
Vector3 worldEuler = gun.eulerAngles;
Vector3 loca