- Home /
Increase Rigidbody2D Velocity based on player direction
Hi everyone
So I have this script below that determines the players rotation in the direction its heading. How do i add a If mouse down function to addForce to its current trajectory?
Any help would be greatly appreciated!!!
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerVelocity : MonoBehaviour {
Vector3 startPos, endPos, direction;
public Rigidbody2D myRigidbody;
public float thrust = 10.0f;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D> ();
transform.position = new Vector3(0.0f, -2.0f, 0.0f);
}
void Update () {
Vector2 moveDirection = myRigidbody.velocity;
if (moveDirection != Vector2.zero) {
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
}
Answer by Overature · Oct 30, 2020 at 04:05 PM
Create an if statement in the update block that detects when the mouse button is down, then modify the position of the object you want to move. Something like this:
if(Input.GetMouseButtonDown(0)){
float distance = 5f;
transform.position = new Vector3(transform.postion.x + transform.position.y + distance,
transform.positon.z)
}
This will move the object by 5 in the y direction every frame that the mouse button is held down. Change the distance value to make it faster or slower or negative if you wish to change direction. You can also add change x and z position in the same manor. I hope that helps.
I actually managed to create the affect i was after!
I just increased my rigidBodys velocity.
see below :)
Vector3 startPos, endPos, direction; public Rigidbody2D myRigidbody;
public float force = 0f;
public float pull = 0f;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D> ();
transform.position = new Vector3(0.0f, -2.0f, 0.0f);
}
public void Update ()
{
Vector2 moveDirection = myRigidbody.velocity;
if (moveDirection != Vector2.zero) {
float angle = $$anonymous$$athf.Atan2(moveDirection.y, moveDirection.x) * $$anonymous$$athf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
if (Input.Get$$anonymous$$ouseButtonDown (0))
{
myRigidbody.velocity /= force;
Debug.Log("forceApplied");
myRigidbody.mass += pull;
Debug.Log("PullApplied");
}
if (Input.Get$$anonymous$$ouseButtonUp (0))
{
myRigidbody.velocity *= force;
Debug.Log("forceReduced");
myRigidbody.mass -= pull;
Debug.Log("PullApplied");
}
}