[英]How to get effectors working on my character unity 2d
我試圖在平台器中使用浮力效應器,但是由於某些原因,由於連接到播放器的控制器腳本使效應器無法工作。 以下是我的控制器腳本。
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;
}
}
當我禁用此腳本時,它可以正常工作。 只是想知道如何使效果器與當前的控制器腳本一起工作。
是這行:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.