r/UnityHelp • u/Fantastic_Year9607 • Dec 07 '21
PROGRAMMING Picking Up Objects
Okay, I am making a 3D physics 3rd person game. I want to make it so that when C is pressed, my player character picks up any object within a hitbox, and carries it around until C is pressed again, causing her to throw it. Here's the code that I'm using for the rest of her movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
CharacterController character;
Collider stomp;
Collider punch;
float moveX;
float moveZ;
float moveY;
Vector3 movement;
private Vector3 rotation;
Vector3 velocity;
public float speed;
public float gravity;
public float rotationSpeed = 180;
public float crouchSpeed = 8;
public float jump = 10f;
bool isGrounded;
public Transform groundCheck;
public LayerMask groundMask;
public float groundDistance = 0.2f;
public float highJump = 25f;
public float sprintSpeed = 25f;
public float distance = 3f;
public float mass = 45f;
//public float stompPower = 1f;
void Start()
{
character = GetComponent<CharacterController>();
stomp = GetComponentInChildren<Collider>();
punch = GetComponentInChildren<Collider>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}
this.rotation = new Vector3(0, Input.GetAxisRaw("Horizontal") * rotationSpeed * Time.deltaTime, 0);
Vector3 move = new Vector3(0, 0, Input.GetAxisRaw("Vertical") * Time.deltaTime);
move = this.transform.TransformDirection(move);
this.transform.Rotate(this.rotation);
character.Move(move * speed);
if (Input.GetKey(KeyCode.Z) && isGrounded)
{
character.height = .75f;
character.Move(move * crouchSpeed);
//stomp.enabled = false;
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(highJump * -2f * gravity);
}
}
//else if (Input.GetKey(KeyCode.Z))
//{
//stomp.enabled = true;
//}
else
{
character.height = 1.5f;
character.Move(move * speed);
//stomp.enabled = false;
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jump * -2f * gravity);
}
}
character.Move(movement * speed*Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
character.Move(velocity * Time.deltaTime);
if (Input.GetKey(KeyCode.LeftShift))
{
character.Move(move * sprintSpeed);
}
else if (Input.GetKeyDown(KeyCode.Z) && Input.GetKeyDown(KeyCode.LeftShift))
{
velocity.z = Mathf.Sqrt(-2f* gravity* distance);
}
else
{
character.Move(move * speed);
}
}
//private void OnTriggerEnter(Collider other)
//{
//var hit = other.GetComponent<Damagable>();
//if (hit != null)
//{
//hit.damage(stompPower);
//}
//}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody rb = hit.collider.attachedRigidbody;
if (rb != null && !rb.isKinematic)
{
rb.velocity = hit.moveDirection * mass;
}
}
}Okay, what do I add?
4
Upvotes