我试图在我的平台游戏中使用浮力效应器,但由于某些原因,由于我的控制器脚本附加到我的播放器,因此效应器不起作用。下面是我的控制器脚本。
using UnityEngine;
using System.Collections;
public class controller : MonoBehaviour
{
public float topSpeed = 15f;
bool facingRight = true;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
GameObject Player, Player2;
int characterselect;
public float jumpForce = 700f;
public LayerMask whatIsGround;
void Start()
{
characterselect = 1;
Player = GameObject.Find("Player");
Player2 = GameObject.Find("Player2");
}
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
float move = Input.GetAxis("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(move * topSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight) //if facing not right then use the flip function
flip();
else if (move < 0 && facingRight)
flip();
}
void Update()
{
if(grounded&& Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
}
{
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
topSpeed = topSpeed * 2;
}
else if (Input.GetKeyUp(KeyCode.LeftShift))
{
topSpeed = 15;
}
}
void flip()
{
facingRight = ! facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
当我禁用此脚本时,它可以正常工作。只是想知道如何让效应器与我当前的控制器脚本一起工作。
答案 0 :(得分:0)
就是这一行:
GetComponent<Rigidbody2D>().velocity = new Vector2(
move * topSpeed,
GetComponent<Rigidbody2D>().velocity.y);
通过设置速度,您将覆盖物理引擎添加的任何速度 - 包括浮力效应器。如果你想保持物理不受浮力效应器的影响,可以选择一些总和。有很多方法可以实现这一点,具体取决于您想要的行为。
我还建议您将Rigidbody2D存储为变量,以节省您和计算机的时间:
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour
{
// ...
Rigidbody2D rbody2D;
void Start() {
// ...
rbody2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate() {
// One simple example of adding to the velocity.
// Adds velocity in the x-axis such that the new x velocity
// is about equal to topSpeed in the direction we are trying to move.
// Note that "Vector2.right * deltaVelX" = "new Vector2(deltaVelX, 0)".
float move = Input.GetAxis("Horizontal");
float deltaVelX = (move * topSpeed) - rbody2D.velocity.x;
rbody2D.velocity += Vector2.right * deltaVelX;
}
}