文章目录
第二部分
Unity Tutorial Part 2: GameObjects
Adding the Rigidbody Component
MonoBehaviour lifetime
Creating Your First Script
创建 PlayerContoller
脚本,并且添加到 SpaceMarine
组件上:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 50.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 pos = transform.position;
pos.x += moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
pos.z += moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position = pos;
}
}
如果脚本识别不了,有可能是下面的包和新版本的dll 冲突了(排除bug,浏览日志
%LOCALAPPDATA%\Unity\Editor\Editor.log
),移除下面的包:
Camera Movement
方法一、摄像机的跟随
调整摄像机的位置和角度,并且设置为 SpaceMarine
的子组件:
方法二、跟随脚本
1.新建空物体 Create Empty
,命名为 CameraMount
。
2.拷贝 SpaceMarine
的 Transform
组件:
Copy Component
3.选择 CameraMount
,进行 Paste Component Values
操作:
4.调整好 Main Camera
的位置,拖动 Main Camera
到 CameraMount
组件上:
5.为 CameraMount
新建脚本 CameraMovement
:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public GameObject followTarget;
public float moveSpeed = 20;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (followTarget != null)
{
transform.position = Vector3.Lerp(transform.position, followTarget.transform.position,
Time.deltaTime * moveSpeed);
}
}
}
6.拖动 SpaceMarine
到 followTarget
上;设置 moveSpeed
为 20。
Adding Gunplay
制作子弹的预制体
1.创建 3D Object\Sphere
,重命名为 Projectile
。
2.为 Projectile
添加 RigidBody
组件,并且取消勾选 Use Gravity
。
3.拖动 Projectile
到 Assets / Prefabs
目录,删除 Hierarchhy / Projectile
。
创建 Gun脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform launchPosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Down");
if (!IsInvoking("FireBullet"))
{
InvokeRepeating("FireBullet", 0f, 0.1f);
}
}
if (Input.GetMouseButtonUp(0))
{
Debug.Log("Up");
CancelInvoke("FireBullet");
}
}
void FireBullet()
{
GameObject bullet = Instantiate(bulletPrefab) as GameObject;
bullet.transform.position = launchPosition.position;
bullet.GetComponent<Rigidbody>().velocity = transform.parent.forward * 100;
}
}
挂载脚本
1.选择 BobbleMarine-Body
,添加 Gun
脚本。
2.展开物体:BobbleMarine-Body
- Armature
- Master Controll
- Hips
- Torso
- Shoulder.R
- Forearm.R
- Hand.R
- Hand.R.1
- Gun.001
- Gun
:
3.选择 Gun
,创建 Create Emoty Child
,命名为 Launcher
。
4.拖动 Launcher
到 Gun Script
的 Launch Position
:
运行游戏
设置Play模式时,编辑器的颜色
Edit - Preference…