我是Unity新手。我正在玩一个2D sidescroller。以下是我要编写的脚本的功能:
目前,唯一有效的是动画转换。我不确定是什么问题。这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Avatar_Manager : MonoBehaviour {
private Animator anim;
private Rigidbody2D rigidbody2D;
private Transform trans;
private int direction;
private bool moving;
public const float acceleration = 1.0f / 180;
public float horizontal_speed;
public float vertical_speed;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
rigidbody2D = GetComponent<Rigidbody2D>();
trans = GetComponent<Transform>();
//Default facing right
direction = 1;
moving = false;
vertical_speed = 0;
}
// Update is called once per frame
void Update () {
//Check direction
if (rigidbody2D.velocity.x < 0)
{
direction = -1;
}
else if (rigidbody2D.velocity.x > 0)
{
direction = 1;
}
// Move right
if (Input.GetKeyDown(KeyCode.D))
{
//Flip Avatar if facing left
if (direction == -1)
{
direction = 1;
trans.rotation.Set(trans.rotation.x, trans.rotation.y + 180, trans.rotation.z, trans.rotation.w);
}
//Start moving
if (!moving)
{
moving = true;
horizontal_speed = 10;
rigidbody2D.velocity = new Vector2(horizontal_speed, vertical_speed);
anim.SetInteger("State", 1);
}
//Update speed
else
{
if(horizontal_speed < 20)
{
horizontal_speed += acceleration;
rigidbody2D.velocity.Set(horizontal_speed, vertical_speed);
}
}
}
//Stop moving right
if (Input.GetKeyUp(KeyCode.D))
{
moving = false;
horizontal_speed = 0;
rigidbody2D.velocity.Set(horizontal_speed, vertical_speed);
anim.SetInteger("State", 0);
}
// Move left
if (Input.GetKeyDown(KeyCode.A))
{
//Flip Avatar if facing right
if (direction == 1)
{
direction = -1;
trans.rotation.Set(trans.rotation.x, trans.rotation.y - 180, trans.rotation.z, trans.rotation.w);
}
//Start moving
if (!moving)
{
moving = true;
horizontal_speed = -10;
rigidbody2D.velocity = new Vector2(horizontal_speed, vertical_speed);
anim.SetInteger("State", 1);
}
//Update speed
else
{
if (horizontal_speed > -20)
{
horizontal_speed -= acceleration;
rigidbody2D.velocity.Set(horizontal_speed, vertical_speed);
}
}
}
//Stop moving right
if (Input.GetKeyUp(KeyCode.A))
{
moving = false;
horizontal_speed = 0;
rigidbody2D.velocity.Set(horizontal_speed, vertical_speed);
anim.SetInteger("State", 0);
}
}
}
答案 0 :(得分:0)
更改此
if (rigidbody2D.velocity.x < 0)
{
direction = -1;
}
else if (rigidbody2D.velocity.x > 0)
{
direction = 1;
}
到这个
if (rigidbody2D.velocity.x < 0)
{
transform.localscale = new Vector3 (-1,1,1);
}
else if (rigidbody2D.velocity.x > 0)
{
transform.localscale = new Vector3 (1,1,1);
}