子弹没有以固定的速度加力?如何在2D中左右独立地正确拍摄?

如何解决子弹没有以固定的速度加力?如何在2D中左右独立地正确拍摄?

我对编码有点陌生,大约一年的经验。我不知道为什么我的脚本不会对以固定速度射击的子弹增加力量。这似乎取决于玩家移动的速度,但是我使用了2个不同的变量作为速度和MovementSpeed,所以我不知道为什么要这么做。我将如何解决这个问题?我也试图做到这一点,以便当角色面对该方向时我可以从左右两侧独立拍摄,但似乎不起作用。当我尝试修复它时,它会抛出错误,实例化时项目符号会保留在原位,或者项目符号总是在右侧。如果我做错了,正确的做法是什么?

using System.Collections.Generic;
using UnityEngine;

public class BulletScript : MonoBehaviour
{
    public GameObject Bullet;
    public float sec = 2f;

    public float speed = 80;

    public GameObject Enemy;

    public Transform spawnPoint;

    public Rigidbody2D bulletRB;

    private float timeBtwShots;
    public float startTimeBtwShots;

    public AudioSource Gunshot;

    public Animator animator;

    private float vert;
    private float horiz;

    // Start is called before the first frame update
    void Start()
    {
        if (gameObject.tag == "Bullet")

            this.gameObject.SetActive(true);

        StartCoroutine(LateCall());

        IEnumerator LateCall()
        {
            yield return new WaitForSeconds(sec);

            this.gameObject.SetActive(false);
        }
       
        
    }

    void OnCollisionEnter2D(Collision2D Other)
    {
        Destroy(this.gameObject);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Enemy")
        {
            this.gameObject.SetActive(false);
            other.gameObject.SetActive(false);
        } 
    }

    IEnumerator ShootingAnim()
    {
       
        timeBtwShots = startTimeBtwShots;
        Gunshot.Play();
        animator.SetBool("IsShooting",true);

        yield return new WaitForSeconds(0.2f);

        animator.SetBool("IsShooting",false);


    }

    void Update()
    {
        horiz = Input.GetAxis("Horizontal");
        vert = Input.GetAxis("Vertical");

        if (Input.GetMouseButtonDown(0))
        {
            Instantiate(bulletRB,spawnPoint.position,Quaternion.identity);
        }
    }

    void FixedUpdate()
    {
        

        if (timeBtwShots <= 0)
        {

                bulletRB.AddForce(transform.TransformDirection(new Vector2(horiz,vert)).normalized * speed);

                StartCoroutine(ShootingAnim());
            }
        else
        {
            timeBtwShots -= Time.deltaTime;
        }
        if (gameObject.tag == "Bullet")
        {
            Destroy(this.gameObject,1f);
        }
    }
}

解决方法

不要使用输入来确定子弹的方向,而要存储玩家所看的方向。添加一个名为“ currentDirection”的新Vector2,并将其默认为Vector2.right或其他名称。计算播放器上的移动时,请执行以下操作:

if (!Mathf.Approximately(horiz,0) || !Mathf.Approximately(vert,0))
    currentDirection = new Vector2(horiz,vert).normalized;

您会注意到第一行检查任一行是否都不为零。我这样做是因为如果两个输入均为0,则方向也为零。我们只想保存玩家输入的最后一个方向,而不是缺少方向。

接下来,子弹还应该具有方向变量。生成项目符号时,将项目符号的方向设置为currentDirection。您只想在生成子弹时执行此操作。如果每隔一帧将子弹的方向设置为玩家当前的输入,那么它将根据玩家的输入不断地改变方向。

然后只是告诉项目符号朝其指定的方向移动。人们通常会改变旋转方向以匹配方向并告诉其前进,但这取决于您希望艺术品寻找子弹的方式。


也非常重要,但又无关紧要:您需要将所有刚体代码放入FixedUpdate中。物理仅在固定更新期间发生,因此执行任何与物理无关的操作都可能导致问题。但是,这样做时,将输入检查保留在Update中。由于FixedUpdates并非在每一帧都发生,因此如果将它们放入FixedUpdate,可能会丢失输入。因此,添加一些输入变量,并在更新中添加

jumpInput = Input.GetButtonDown("Jump");
horiz = Input.GetAxis("Horizontal");
vert = Input.GetAxis("Vertical");

然后在FixedUpdate中,您的物理过程就像:

if (jumpInput && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
,

最后弄清楚了。我做了一个完整的重写,因为我使代码过于复杂。 这是最终的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float MovementSpeed = 1;
    public float JumpForce = 1;
    public float jumpTime = 1f;

    public Rigidbody2D _rigidbody;

    private bool facingRight;

    public float sec = 2f;

    public Vector2 bulletPos;

    public GameObject bulletToRight,bulletToLeft;

    public Transform spawnPoint;

    public Rigidbody2D bulletRB;

    public AudioSource Gunshot;

    float horizontalMove = 0f;

    public float fireRate = 0.5f;
    float nextFire = 0f;

    // public AudioSource Jump;

    public Animator animator;

    void HandleMovement(float horizontal)
    {
        transform.position += new Vector3(horizontal,0) * Time.deltaTime * MovementSpeed;
        animator.SetFloat("velX",(horizontal));
    }

    void Flip(float horizontal)
    {
        if (horizontal < 0 && !facingRight || horizontal > 0 && facingRight)
        {
            facingRight = !facingRight;

            Vector3 theScale = transform.localScale;

            theScale.x *= -1;

            transform.localScale = theScale;

            transform.position += new Vector3(horizontal,0) * Time.deltaTime * MovementSpeed;

            horizontalMove = Input.GetAxisRaw("Horizontal") * MovementSpeed;

            animator.SetFloat("velX",(horizontalMove));
        } 
    }

    IEnumerator ShootingAnim()
    {

        
        animator.SetBool("IsShooting",true);

        yield return new WaitForSeconds(0.2f);

        animator.SetBool("IsShooting",false);


    }

    void Update()
    {

        animator.SetFloat("velX",Mathf.Abs(horizontalMove));

        if (Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y) < 0.001f)
        {
            _rigidbody.AddForce(new Vector2(0,JumpForce),ForceMode2D.Impulse);
            animator.SetBool("IsJumping",true);
            // Jump.Play();
        }

        if (Mathf.Abs(_rigidbody.velocity.y) == 0f)
        {
            animator.SetBool("IsJumping",false);
        }

        if ((_rigidbody.velocity.x) >= 0.01f || (_rigidbody.velocity.x <= -0.01f)) 
        {
            animator.SetBool("IsRunning",true);
        }

        if (Input.GetMouseButtonDown(0) && Time.time > nextFire)
        {
            StartCoroutine(ShootingAnim());
            nextFire = Time.time + fireRate;
            Fire();

        }


        float horizontal = Input.GetAxis("Horizontal");

        HandleMovement(horizontal);

        Flip(horizontal);



    }

    void Fire()
    {
        bulletPos = spawnPoint.position;
        if (!facingRight)
        {
            bulletPos += new Vector2(+0.02f,0f);
            Instantiate(bulletToRight,bulletPos,Quaternion.identity);
            Gunshot.Play();
        } else
        {
            bulletPos += new Vector2(-0.02f,0f);
            Instantiate(bulletToLeft,Quaternion.identity);
            Gunshot.Play();
        }
        
    }
}

这是BulletScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletScript : MonoBehaviour
{
    public GameObject Bullet;

    public Transform spawnPoint;

    public Rigidbody2D bulletRB;

    public float velX = 5f;

    float velY = 0f;

    // Start is called before the first frame update
    void Start()
    {
        bulletRB = GetComponent<Rigidbody2D>();
    }

    void OnCollisionEnter2D(Collision2D Other)
    {
        Destroy(this.gameObject);
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Enemy")
        {
            this.gameObject.SetActive(false);
            other.gameObject.SetActive(false);
        } 
    }

    private void Update()
    {

        bulletRB.velocity = new Vector2(velX,velY);
        Destroy(gameObject,3f);

    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res