Question by
toadflaxunf · Dec 23, 2017 at 10:09 PM ·
physicsunity5velocitythrowing
Throw Ball Forwards
I have written a script that allows me to pick up a ball and move it around according to my mouse position:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class dragObject : MonoBehaviour {
float distance = 2;
public Camera Stall; // stall camera
void OnMouseDrag()
{
Stall = GameObject.Find("Stall Camera").GetComponent<Camera>();
Vector3 mousePosition = new Vector3(Input.mousePosition.x,
Input.mousePosition.y, distance);
Vector3 objPosition = Stall.ScreenToWorldPoint(mousePosition);
transform.position = objPosition;
if (Input.GetKeyDown(KeyCode.F))
{
// When F is pressed, launch the ball forwards on the Z axis
}
}
}
But I can't figure out a way of getting the ball to launch forwards in the if statement
without the sphere just flashing instead of actually moving.
Thank in advance
Comment
Answer by Alanisaac · Dec 23, 2017 at 10:37 PM
In general, to simulate "physics stuff", Unity provides a helpful component called a Rigidbody. You can find more information in Unity's main tutorials.
Essentially, you'll want to give the ball a rigidbody component. With that component you can do things like add force in a specific direction, or simply set a velocity. You can also make use of gravity, if you want to.