地图添加Tilemap Collider 2D
快速创建主角及动画
起个名字保存一下
界面上已经有人物了,点击运行,可以看到idle动画,给人物idle添加Circle Collider 2d和Rigidbody 2D,然后将idle重命名为player,设置Rigidbody 2D的z轴锁定,防止移动时翻跟头
动画拖不进去的解决办法,不知道为什么,教程可以直接拖进去,我的就是不行,应该是没找对方法,可以通过另种方法实现动画制作
拖动所有素材到Hierarchy
起个名字
删掉没有的动画等
修改playerAnimation动画,run后期修改成了runing类型改成float了,方便动画切换
把条件统统设置上去,并且动画切换时间改为0
run->idle
idle->run
jump->idle
idle->jump
run->jump
jump->run
给主角添加脚本
安装屏幕方向组件,assetstore搜索Joystick Pack添加到我的资源,导入到项目
添加Canvas并将Variable joystick拖动给Canvas
调整分辨率和Joystick位置
Cravity Scale重力修改为3方便快速下落
添加一个Background图层
将地图设置到Background图层
将资源幅值给player中的脚本
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PlayerControler : MonoBehaviour
{
[SerializeField] private Rigidbody2D PlayerRd;
[SerializeField] private Animator PlayerAnimator;
public Collider2D PlayerCollider;
public float Speed;
public float Jumpforce;
public LayerMask Ground;
public VariableJoystick variableJoystick;
// Start is called before the first frame update
void Start()
{
PlayerRd = GetComponent<Rigidbody2D>();
PlayerAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Movement();
SwithcAnim();
}
void Movement()
{
float horizontalMove = variableJoystick.Horizontal;
float verticalMove = variableJoystick.Vertical;
#region 设置
PlayerRd.velocity = new Vector2(horizontalMove * Speed * Time.deltaTime, PlayerRd.velocity.y);
PlayerAnimator.SetFloat("runing", Mathf.Abs(PlayerRd.velocity.x));
//跳跃和落地
if (verticalMove > 0.5f && ((PlayerCollider.IsTouchingLayers(Ground))))
{
PlayerRd.velocity = new Vector2(PlayerRd.velocity.x, Jumpforce);
}
if (horizontalMove > 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
else if (horizontalMove < 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
#endregion
}
void SwithcAnim()
{
if (PlayerCollider.IsTouchingLayers(Ground))
{
PlayerAnimator.SetBool("jump", false);
}
else if(Mathf.Abs(PlayerRd.velocity.y) > 10)
{
PlayerAnimator.SetBool("jump", true);
}
}
}
最终效果
有时走动会发现忽快忽慢,是因为碰撞器产生了向上的力后地面的摩擦力就小了,有一种比较简单的解决办法,就是直接改变player的位置,修改后的代码
void Movement()
{
float horizontalMove = variableJoystick.Horizontal;
float verticalMove = variableJoystick.Vertical;
#region 设置
PlayerRd.transform.position = new Vector2(horizontalMove * Speed * Time.deltaTime + PlayerRd.transform.position.x, PlayerRd.transform.position.y);
PlayerAnimator.SetFloat("runing", Mathf.Abs(horizontalMove));
//跳跃和落地
if (verticalMove > 0.5f && ((PlayerCollider.IsTouchingLayers(Ground))))
{
PlayerRd.velocity = new Vector2(PlayerRd.velocity.x, Jumpforce);
}
if (horizontalMove > 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
else if (horizontalMove < 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
#endregion
}
需要调整一下速度值