首页 > 解决方案 > 如何在unity2d中碰撞后向物体添加力,以模拟用球棒击打棒球

问题描述

我正在开发一个 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));
         }
     }
 }

但是,当我按下空格键时,我无法踢球。由于对撞机,球只是弹跳。我错过了什么?

检查我的结果:

.gif 图像

标签: c#unity3d

解决方案


我会提倡更像这样的东西开始。这是您要添加到棒球棒上的脚本。

第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。因此,在再次按住空格键之前,后续的碰撞不会导致击中。

让我知道这是否对您有任何帮助。


推荐阅读