【发布时间】:2018-12-27 00:53:39
【问题描述】:
我一直在关注 Unity 中有关 2D 播放器控制器的教程(它是“2013 年 12 月 16 日的实时培训 - 2D 角色控制器”视频)。
我能够通过一些编辑成功实现教程中显示的所有内容,使其在 Unity 5 中运行。之后,我决定尝试一下,以便更好地理解。我尝试做的一件事是在按下 Space 键时改变跳跃高度。代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RobotControllerScript : MonoBehaviour {
public float maxSpeed = 10f;
bool facingRight = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700f;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate () {
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
anim.SetBool("Ground", grounded);
//vSpeed = vertical speed
anim.SetFloat("vSpeed", GetComponent<Rigidbody2D>().velocity.y);
float move = Input.GetAxis("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(move));
GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed,
GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight)
{
Flip();
}
else if (move < 0 && facingRight)
{
Flip();
}
}
void Update()
{
if(grounded && Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("Ground", false);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
查看代码和教程解释,jumpForce 是控制角色跳跃高度(施加力)的变量。所以,我把 700f 改成了 5f。我希望这个角色能做出一个非常小的跳跃,但事实并非如此。它以与 700f 相同的高度跳跃。
public float jumpForce = 700f;
在玩弄了代码之后,我可以通过删除 jumpForce 旁边的“public”来获得预期的结果。解决此问题的其他方法是将其设置为私有或静态。我记得我在 QT Creator 上制作温度小部件时遇到了类似的问题。我必须将变量设置为静态,否则在 C 到 F 转换后它不会返回默认值,但我不记得确切原因。
谁能解释为什么“公共”不起作用以及为什么私有/静态/无可能?这个问题的最佳/有效解决方案是什么?非常感谢。
【问题讨论】:
-
你在哪里把 700 改成了 5?在检查员或代码中?如果在检查器中,您是处于播放模式还是编辑模式?如果在代码中,您是否在变量声明或方法内部进行了更改,例如 update 或 start?
-
我改变了公共浮动 jumpForce = 700f;到公共浮动 jumpForce = 5f;在代码中(C# 脚本)
-
检查检查员。公共字段会自动序列化,这意味着该字段在检查器中设置为
700并覆盖您的新5
标签: c# unity3d access-modifiers