Kicking at 45° direction
I want to kick a ball forward with a 45° elevation, my best thought is to use Vector3, however I cannot figure out how to make a Vector3 that does it, the best i´ve been able to do so far is to kick it with a semi-circle elevation, but my intention is to kick it like this...
Is there a way to make this kind of vector? Or am I totally wrong using Vector3?
Could you insert some of your code? I would like to see how the ball gets kicked, is there a RigidBody that gets an AddForce call, or what is it.
This is what i´m using right now, it works well, however I´d still wish I could achieve a straight direction like in the pictures...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class striking : $$anonymous$$onoBehaviour
{
public float power = 20;
void Update()
{
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.RightShift))
TryHitBall();
}
void TryHitBall()
{
if (power > 0)
{
Rigidbody rb = GetComponent<Rigidbody>();
rb.velocity = StrikeVec() * power;
}
}
private Vector3 StrikeVec()
{
Vector3 elevation = new Vector3 (0,0.8f,0);
Vector3 sight = Camera.main.transform.forward;
Vector3 fixsight = sight - new Vector3 (0,0.2f,0);
Vector3 direction = fixsight + elevation;
return direction.normalized;
}
}
Answer by KoenigX3 · Jan 18, 2017 at 09:57 AM
You can use the Rigidbody.useGravity property to disable gravity. That will make the ball fly like it would in space. Later on you can enable the gravity for the ball if you want.
void TryHitBall()
{
if (power > 0)
{
Rigidbody rb = GetComponent<Rigidbody>();
rb.useGravity = false;
rb.velocity = StrikeVec() * power;
}
}
For example, if the net has a collider on it, you can use that to reactivate the gravity for the ball.
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Goal")
{
GetComponent<Rigidbody>().useGravity = true;
}
}
One more thing. If you want to use the Rigidbody more than once, it is a good idea to create a global variable of it, and assign it on the start. This way you will get rid of using GetComponent every time you want to do something with the ball, which will make it more performance-efficient. Put a Rigidbody variable next to the public power float, and assign it on Start().
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
Excellent.
That did it, I actually had no idea of the ".useGravity" function.
Thanks for sharing your knowledge.
Your answer
Follow this Question
Related Questions
How too climb a ladder with the FPS Controller correctly 0 Answers
Vector question 0 Answers
how can I "play" the whole MoveTowards sequence after one click? 1 Answer
Get All Game Objects Between 2 Points 1 Answer
Get Vector3 From Another Script 1 Answer