Need help adding velocity to object when it's clicked (2D image).
Hi folks, any help would be greatly appriciated.
So I'm trying to build a simple mechanic where a bar (canvas image) bounces between two walls and you can click the bar (while it's moving) to increase its velocity. I've got the bouncing working and can give it an initial velocity with one click anywhere on the screen. But I need to have it only react when I actually hit the bar and I want the velocity to be additive so that each time I click it goes faster and faster.
Here's the code I've got so far (attached to the bar):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bounce : MonoBehaviour {
public GameObject bouncer;
public Rigidbody2D rb2d;
public bool headingleft = false;
public float momentum;
public void tapBounce () {
if (headingleft == false) {
this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (momentum, 0f);
} else if (headingleft == true) {
this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (-momentum, 0f);
}
}
void OnCollisionEnter2D (Collision2D other) {
if (other.gameObject.tag == "right") {
headingleft = true;
} else if (other.gameObject.tag == "left") {
headingleft = false;
}
}
void Awake () {
rb2d = bouncer.GetComponent<Rigidbody2D> ();
}
// Use this for initialization
void Start () {
momentum = 100f;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
tapBounce ();
}
}
}
PS: I'm using a Physics Material 2D for the bounciness.
Answer by NoDumbQuestion · Jul 20, 2018 at 01:58 AM
Add Collider to the bar. Use function OnMouseDown on your script.
https://answers.unity.com/questions/373818/how-to-detect-mouse-click-on-a-gameobject.html
Your answer
Follow this Question
Related Questions
is there a way to detect OnMouseDown on a UI image? 2 Answers
Problem with Swap Image in Unity 5 with C#. 2 Answers
Changing Unity.UI.Panel Color 3 Answers
How to make an object the root of a prefab, or remove the canvas that is set as the root of a prefab 0 Answers
Android Camera does not show Image 1 Answer