简体   繁体   English

Unity弹跳精灵

[英]Unity Bouncing Sprite

So I currently drafted up this code to make a simple sprite bounce, now I am a complete begineer when it comes to code and I'd like to understand how to accomplish. 因此,我目前正在起草此代码以进行简单的sprite弹跳,现在我是一个完全入门的代码初学者,我想了解如何实现。 Currently the ball bounces on screen tap but I want it to bounce on ball tap, and the ball should bounce in random directions only within the parameters of the screen. 目前,球会在屏幕点击时反弹,但我希望它在球点击时反弹,并且球应该仅在屏幕参数范围内沿随机方向反弹。

  1. The ball to only bounce specifically when it is tapped 仅在轻拍时反弹
  2. The ball to bounce in random directions within the screen(forward, left, right) 要在屏幕内的任意方向反弹的球(向前,向左,向右)

Here is the code on Unity using c# 这是使用c#在Unity上的代码

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

public class BallBounce : MonoBehaviour {
    Vector3 velocity = Vector3.zero; 
    public Vector3 gravity;
    public Vector3 bounceVelocity;
    public float maxSpeed = 5f; 

    bool didBounce = false; 

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0)) {
            didBounce = true; 
        }

    }

    void FixedUpdate () { 
        velocity += gravity * Time.deltaTime;

        if (didBounce == true) {
            didBounce = false;
            velocity += bounceVelocity;
        }

    velocity = Vector3.ClampMagnitude (velocity, maxSpeed); 
    transform.position += velocity * Time.deltaTime;

    }
}

Video Link: https://youtu.be/XibbUBGdFOc 视频链接: https : //youtu.be/XibbUBGdFOc

First of all add a tag to your ball (in this case I'll use "ball" as tag) 首先,在您的球上添加标签(在这种情况下,我将使用“ ball”作为标签)
Then cast a Raycast. 然后投射光线。 With this you'll get if the user clicked on the ball. 有了这个,您将获得用户单击球的信息。 If he did, then all you'll have to do is to set didBounce to true. 如果他这样做了,那么您要做的就是将didBounce设置为true。

if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButtonDown (0)) {
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
        if (hit.transform.tag == "ball") {
            didBounce = true;               
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM