我在撰寫一個通過按下按鈕拋出生成的球的函式時遇到問題。到目前為止,我只能實體化球,它受重力影響。我不能把頭繞起來,我應該如何在我的代碼中添加一個力來用一些力推動它。現在它只是在玩家面前撲通一聲。
我試圖在一個球剛體 2D 上擺弄 .AddForce() ,但仍然沒有。
如果有人可以查看代碼并指導我了解 AddForce 使球移動的位置,我將不勝感激?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour
{
[Header("Player Atributes")]
[SerializeField] float runSpeed = 10f;
Vector2 moveInput;
Rigidbody2D playerRigidbody2D;
[Header("Ball Settings")]
public bool playerHasABall = false;
[SerializeField] GameObject ball;
[SerializeField] Transform ballSpawn;
void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
}
void Update()
{
Run();
FlipSprite();
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
void Run()
{
Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, playerRigidbody2D.velocity.y);
playerRigidbody2D.velocity = playerVelocity;
}
void FlipSprite()
{
bool playerHasHorizontalSpeed = Mathf.Abs(playerRigidbody2D.velocity.x) > Mathf.Epsilon;
if (playerHasHorizontalSpeed)
{
transform.localScale = new Vector2 (Mathf.Sign(playerRigidbody2D.velocity.x), 1f);
}
}
//Ball picking up script. It destroys the ball with a tag "Ball" and sets a bool playerHasABall to true
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Ball")
{
Destroy(other.gameObject);
playerHasABall = true;
}
}
}
uj5u.com熱心網友回復:
所以,我設法再次擺弄 .AddForce() 方法,我想出了一個解決我的問題的方法。
我的 OnFire 腳本如下所示:
void OnFire(InputValue value)
{
if(!playerHasABall) {return;}
Instantiate(ball, ballSpawn.position, transform.rotation);
playerHasABall = false;
}
這里沒有變化。我制作了另一個名為“BallBehaviour.cs”的腳本,并使用如下代碼將其添加到球中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBehaviour : MonoBehaviour
{
[SerializeField] float ballForce = 20f;
PlayerControl player;
void Start()
{
player = FindObjectOfType<PlayerControl>();
Throw();
}
public void Throw()
{
GetComponent<Rigidbody2D>().AddForce(player.transform.localScale * ballForce, ForceMode2D.Impulse);
}
}
基本上,Throw() 方法告訴球檢查玩家面對的方向,然后將其乘以 ballForce。然后,它使用 ForceMode2d.Impulse 方法將計算出的力施加到球上一秒鐘,并在左或右方向上作業。
感謝 Jkimishere 朝正確的方向輕推!
uj5u.com熱心網友回復:
您可能需要一個變數來檢查玩家是否面向右/左。如果球員是,只需根據方向向球施加力即可。
if(!playerHasABall) {return;}
Instantiate(ball,
ballSpawn.position,
transform.rotation);
//Check which way the player is facing and add forrce to that direction.
//Adding a FacingRight boolean might help.....
playerHasABall = false;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477594.html
上一篇:使用新輸入系統處理不同的函式呼叫
