我是团结的新手,我正在关注一个关于2D平台游戏的脚本的youtube指南,我现在已经到了这一点,当我转向相反的时候我试图为精灵添加一个翻转方向。
我添加了一个代码,现在这个代码不断从左到右翻转。如果我理解正确,可能是因为我一直在申请> 0.1f在移动时导致功能连续运行但老实说我迷失了所以任何帮助都会受到赞赏。
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Controller2D))]
public class Player : MonoBehaviour {
public float jumpHeight = 4;
public float timeToJumpApex = .4f;
float accelerationTimeAirbourne = .2f;
float acceleratinTimeGrounded =.1f;
public float moveSpeed = 6;
float jumpVelocity;
float gravity;
Vector3 velocity;
float velocityXSmoothing;
Controller2D controller;
void Start(){
controller = GetComponent<Controller2D>();
gravity = -(2 * jumpHeight) / Mathf.Pow (timeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
print ("gravity: " + gravity + " Jump Velocity: " + jumpVelocity);
}
void Update(){
if (controller.collisions.above || controller.collisions.above) {
velocity.y = 0;
}
Vector2 input = new Vector2 (Input.GetAxisRaw ("Horizontal"),
Input.GetAxisRaw ("Vertical"));
if (Input.GetKeyDown (KeyCode.Space) && controller.collisions.below) {
velocity.y = jumpVelocity;
}
float targetVelocityX = input.x * moveSpeed;
velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref
velocityXSmoothing, (controller.collisions.below)?
acceleratinTimeGrounded:accelerationTimeAirbourne);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
void FixedUpdate(){
if ((Input.GetAxis("Horizontal") > 0.1f && this.transform.localScale.x != 1)
|| (Input.GetAxis("Horizontal") < -0.1f && this.transform.localScale.x !=
-1))
{
flip();
}
}
void flip()
{
this.transform.localScale = new Vector3(this.transform.localScale.x *
-1,
this.transform.localScale.y, this.transform.localScale.z);
}
}
答案 0 :(得分:2)
您的错误在这里
void FixedUpdate(){
if ((Input.GetAxis("Horizontal") > 0.1f && this.transform.localScale.x != 1)|| (Input.GetAxis("Horizontal") < -0.1f && this.transform.localScale.x !=
-1)){
flip();
}
}
翻转后,条件仍然评估为true。您将需要一个布尔值hasflipped
来检查您是否已经翻转,如果您没有再次翻转:)
固定更新导致每帧检查发生一次,所以当你的精灵翻转每一帧时,你会得到一堆闪烁,除非你只指定翻转一次