【Unity教程】从0编程制作类银河恶魔城游戏】

lesson: 10 - 12

【113.Craft】

补档,上述视频缺失章节 (来源:视频评论区)

素材资源文件


Input.GetButtonDown("Jump") 通过名称Jump可获取点击事件

void Update()
{
if ( Input.GetButtonDown("Jump")) {
Debug.Log("Jump");
}
}

UnityEdit\Project settings下可以找到输入设置

Rigidbody2D需要和Player(小球)建立关联关系

点击space空格实现小球跳跃

C# 端代码示例

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

public Rigidbody2D rb;

public float moveSpeed;
public float jumpForce;
private float xInput;

// Start is called before the first frame update
void Start()
{
Debug.Log("Jump");
}

// Update is called once per frame
void Update()
{
// 获取水平输入
xInput = Input.GetAxisRaw("Horizontal");

rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);

if ( Input.GetKeyDown(KeyCode.Space)) {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
Debug.Log(DateTime.Now+"点击跳跃");
}
}
}

C# 端代码示例

私有化相关变量

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{

private Rigidbody2D rb;

// SerializeField 修饰符可以使私有变量在Unity编辑器中显示
[SerializeField] private float moveSpeed;
[SerializeField] private float jumpForce;
private float xInput;

// Start is called before the first frame update
void Start()
{
// 获取刚体组件
rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
// 获取水平输入
xInput = Input.GetAxisRaw("Horizontal");

rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);

if ( Input.GetKeyDown(KeyCode.Space)) {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
Debug.Log(DateTime.Now+"点击跳跃");
}
}
}


示例新增: Capsule Collider 2D 是一个用于2D物理系统的碰撞器组件。

快捷切图,就不用先点apply,在点Sprite Editor

小精灵切图注意

图像过滤模式设置


小精灵.png切图,并选择材质赋予对象,最终效果预览

小精灵.png ( 某度网盘 )

需要冻结Z轴,不然图片素材会物理特性导致倾倒。

这里由于切图出来的小精灵不一定在居中位置,所以在父类Player下通过点击Create Empty创建GameObject对象,并通过调整位置,将父类和子类的中心点接近一致,在将小精灵材质赋予Animator对象。