c# - 如何在unity2d中碰撞后向物体添加力,以模拟用球棒击打棒球
问题描述
我正在开发一个 2D 游戏项目。我希望用户在按下“空格”键时能够击球。我分配了;
- 圆形对撞机 2D 和 Rigidbody 2D 到球
- 刚体 2D 和 Box Collider 2D 到英雄
- Edge Collider 2D 到棒球棒。
这是我称之为“KickTheBall.cs”的脚本:
using UnityEngine;
using System.Collections;
public class KickTheBall : MonoBehaviour {
public float bounceFactor = 0.9f; // Determines how the ball will be bouncing after landing. The value is [0..1]
public float forceFactor = 10f;
public float tMax = 5f; // Pressing time upper limit
private float kickStart; // Keeps time, when you press button
private float kickForce; // Keeps time interval between button press and release
private Vector2 prevVelocity; // Keeps rigidbody velocity, calculated in FixedUpdate()
[SerializeField]
private EdgeCollider2D BatCollider;
private Rigidbody2D rb;
void Start () {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
if(kickForce != 0)
{
float angle = Random.Range(0,20) * Mathf.Deg2Rad;
rb.AddForce(new Vector2(0.0f,
forceFactor * Mathf.Clamp(kickForce, 0.0f, tMax) * Mathf.Sin(angle)),
ForceMode2D.Impulse);
kickForce = 0;
}
prevVelocity = rb.velocity;
}
void Update(){
if(Input.GetKeyDown (KeyCode.Space))
{
kickStart = Time.time;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if(hit.collider.name == "Ball") // Rename ball object to "Ball" in Inspector, or change name here
kickForce = Time.time - kickStart;
}
}
}
public void KickBall(){
BatCollider.enabled = true;
}
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "Ground") // Do not forget assign tag to the field
{
rb.velocity = new Vector2(prevVelocity.x,
-prevVelocity.y * Mathf.Clamp01(bounceFactor));
}
}
}
但是,当我按下空格键时,我无法踢球。由于对撞机,球只是弹跳。我错过了什么?
检查我的结果:
解决方案
我会提倡更像这样的东西开始。这是您要添加到棒球棒上的脚本。
第1部分:
using UnityEngine;
using System.Collections;
public class KickTheBall : MonoBehaviour
{
public float forceFactor = 10f;
private float kickForce = 50f;
void OnCollisionEnter(Collision col)
{
if(col.gameObject.tag == "Ball") // Do not forget assign tag to the field
{
rb = col.gameobject.GetComponent<Rigidbody>();
rb.AddForce(transform.right * kickForce);
}
}
}
出于演示目的,我已经简化了您的 AddForce 函数。如果一切正常,请随意用更复杂的 AddForce 函数替换它。
第2部分:
如果您真的想包含按住空格键会使击打更强的部分,请添加以下内容:
void Update()
{
if(Input.GetKey(KeyCode.Space))
{
kickForce += 0.5f;
}
}
并在 oncollisionenter 末尾添加
kickForce = 0;
这将做的是在你按住空格键的同时增加力量。成功击中后,力将重置为 0。因此,在再次按住空格键之前,后续的碰撞不会导致击中。
让我知道这是否对您有任何帮助。
推荐阅读
- c# - 在按钮单击中添加 JSON 层 - Xamarin.Forms
- ruby - 用 Elixir 代替 sidekiq 工作:我如何了解并发性?
- arrays - 如何在 Swift 中检查另一个数组中的多个对象?
- ckeditor - 如何在ckeditor5中链接从Google Drive中提取的URL图像
- javascript - 如何在 tensorflow.js 神经网络中使用文本作为输入
- swift - 在节点的右边缘而不是在中心旋转 SKSpriteNode
- gulp - Gulp 泵错误:错误:泵至少需要两个流
- java - 如何将 TreeMap 写入 .txt 文件?
- angular - 如何在 Angular Dart 中使用最新版本的 d3 js 库?
- python - Calculating time to disk full for n processes downloading to available storage