I’m trying to get my bearings around unity regarding the physics and AddForce doesnt behave as i’m expecting it to…
using UnityEngine;
using System.Collections;
using System;
public class PickUpScript : MonoBehaviour
{
private GameObject _mainCamera;
private bool _isCarrying;
private GameObject _carriedObject;
private Vector3 _relativeRotation;
private float _accumelatedForce = 0;
private bool _isThrowing;
public float _distanceFromSelf;
public float _transitionSmoothness;
// Use this for initialization
void Start()
{
_mainCamera = GameObject.FindWithTag("MainCamera");
}
// Update is called once per frame
void Update()
{
if (_isCarrying)
{
CarryItem(_carriedObject);
CheckThrow();
CheckDrop();
}
else
{
PickUp();
}
}
private void CheckThrow()
{
if (Input.GetKey(KeyCode.T))
{
_isThrowing = true;
_accumelatedForce += Time.deltaTime;
}
else
{
if (_isThrowing)
{
int x = Screen.width / 2;
int y = Screen.height / 2;
var ray = _mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y)).direction;
_carriedObject.GetComponent<Rigidbody>().AddForce(ray * _accumelatedForce, ForceMode.Impulse);
DropObject();
_accumelatedForce = 0;
_isThrowing = false;
}
}
}
private void PickUp()
{
if (Input.GetKeyDown(KeyCode.E))
{
int x = Screen.width / 2;
int y = Screen.height / 2;
var ray = _mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10)
&& hit.collider.GetComponent<PickUpable>() != null)
{
_isCarrying = true;
_carriedObject = hit.collider.gameObject;
_relativeRotation = _carriedObject.transform.rotation.eulerAngles - gameObject.transform.rotation.eulerAngles;
}
}
}
private void CheckDrop()
{
if (Input.GetKeyDown(KeyCode.E))
{
DropObject();
}
}
private void DropObject()
{
_isCarrying = false;
_carriedObject = null;
}
private void CarryItem(GameObject item)
{
item.transform.position = _mainCamera.transform.position + _mainCamera.transform.forward * _distanceFromSelf;
item.transform.LookAt(gameObject.transform);
item.transform.eulerAngles += _relativeRotation;
}
}
on CheckThrow, i’m trying to push the object (a generic cube) which i’m holding away from me.
but regardless of the force vector i’m setting in, the cube is awlays pushed down towards the ground.
I’ve tried setting different vectors but no effect has been noticed…
any ideas?