• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By aymen
      please any know how can i' calculate the centroid from any number vertices
    • By Henry Fernandez
      Good day sir/maam. I am developing a game for my thesis and im done with multiplayer and plan to start the implementation of AI but i dont know how/where to start. Please give an advice. I am developing it in C# using UNITY. 
      Im am now collected all pieces that has possible moves but i am stuck on which best move to select. I hope you will help me. This is link explained the game https://en.wikipedia.org/wiki/Game_of_the_Generals 

    • By Priceman
      Firstly, hello to everyone.
      So, as the title says, i'm looking for a bit of direction for designing and programming my game idea. What i'm essentially trying to do is create a 2d side scroller along the lines of such titles as Dust: An Elysian Tail, Ori and the Blind Forest, or the Odin Sphere series. I'm currently taking courses on Udemy to learn unity and C#. I chose this route since one of my favorite indie dev studios, Ska Studios, use it making their games. I'm already a decent artist and animator, so I just need something to put the pieces together. I guess i'm looking for an opinion on if this is the best route to take for someone completely new to game development and programming. I've looked into engines like gamemaker, but for what I have in mind (progression systems, inventories, etc) it didn't seem like the way to go. RPGmaker and Unreal also don't seem to be right for what I have in mind. 
      Anyway, thanks for taking the time to help.
    • By fr0st2k
      Hello All.
      I have been working with a small team the last few months on development of a mobile RPG/gacha game, inspired by games like: Brave Frontier, Summoners War, One Piece Treasure Cruise, and even Diablo. 
      The idea behind the game is to create a fun collection game that has a good amount of strategy, with a focus on creating a true game for gamers.  Not a corporate run money grabber like the majority of mobile games.
      We have done a lot of work already on the game, however, I am at a point now where I need dedicated team members who have a passion for game development and the project.
      Take a look at some of the screenshots of the game to get an idea of where we are.
      The game involves collecting characters, and leveling them, to compete against more difficult encounters.  I took a lot of inspiration from my days playing Diablo 2.  If you boil down diablo's gameplay mechanics, you get a core game based around efficiency.  The better your items, the faster you can clear zones to the bosses, and the safer the battle with the bosses are.  After you kill the boss, you pull a slot machine lever and get more items.  The better your character(and skill), the more chances you get at pulling that slot machine lever.
      This game uses that core mechanic in a mobile environment.  Instead of running through Act3 to mephisto, you send your characters out on an 'explore' mission.  A specific amount of time goes by based on your characters power, then you fight a strategic boss fight, where you can win loot.  The explore times range from a few minutes, to hours/days.  You can speed up that time by playing a 'tap' game, similar to Tap Titans.  
      It is a great formula, and even without proper balancing, the game is already shaping up to be a lot of fun.
      --- What I need moving forward:
      Team requirements:
      1. Lead developer / Senior Programmer (unity)
      We need someone who is very fluent in unity game development, and someone who can lead a team of newer programmers. If you have been looking for a project that you can take control of, or need some resume building work that will provide a finished product to show off, this is a great position to fill, as the game is nearly complete already.
      Ideally, this candidate would be proficient in unity client and server side programming
      If you are interested in the position, we can talk profit sharing once the app launches.  (contracts will be required)
      2. Programmers
      If you are newer to programming, or just want to sharpen your skills and gain some experience on a game development team, reach out.  I'd be interested in talking to you and seeing if you are a good fit. 
      I suspect an NDA might be required, but other than that, this position would be great to hop in and out of, and again, would be a great way to contribute to a great project and gain valuable experience.
      3. Pixel Artist / Spine animator
      Either or.  I am currently getting art from a team out in Indonesia.  They are great, but hard to communicate with.  I'd love to have a dedicated artist with Spine(or any alternative 2d pixel animation) experience.  
      If you have interest in joining this team, please reply back.  Again, i'd like to reiterate, this is primarily a hobby based project.  However, it will eventually hit the app store and (ideally)generate income.  All team members will be a part of that revenue stream.
      Please respond with any questions, would be happy to respond.

    • By Nostalgic Saint

      Trap.io is a game where you collect the trap power-ups and place them and then lead the corresponding enemy (based on color) into the trap to destroy the enemy and score points.The game is endless easy to play difficult to master. The game features highly fast paced combat with an arcade-like feel to movement, to bring back the nostalgia from the past retro space shooter games. With addictive fast paced gameplay a mistake might be your last, keeping up with the fast paced flow games typically lasting 2 minutes, this game is all about fast movement and quick thinking with an element of strategy to trick your cunning, wity enemies into the traps to score points

  • Advertisement
  • Advertisement
Sign in to follow this  

Unity Pickup and Throw Script Unity

This topic is 451 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am relatively new to game development and am having a huge problem in my game scripts.  I was following this tutorial, -> 

 , on how to pickup and drop objects.

I've gotten it to work fine for that purpose but I have been trying to add functionality for throwing and seem to have hit a wall (pun intended).  It's a literal wall in fact, since every time I throw the object it goes in the same direction no matter which direction I am facing. 


I have tried numerous other tutorials to no avail.  Either they are outdated or not relevant or broken in some way that I cannot fathom.

I have also tried writing my own from scratch with multiple different ideas on how to accomplish the task , also to no avail.


 Nothing I do seems to work and somewhere along the line I did something that broke my game completely.  SO much so that even removing every script in the scene still rendered it unplayable....So now I am remaking it and am scared to death of the idea I might break the engine again.


Here are the things that I have tried so far:  

Locking the rotation on pickup

Setting a new rotation on throw

setting the rotation to (0,0,0) then throwing

and numerous other slight tweaks to get it to go the direction it is facing


Unfortunately I am a giant noob and can't get anything I try to actually do what I want it to even though I thought I had a pretty good grasp on what I had to do....


Also the object rotates freely in my "hand" and moves when it bumps other objects but this still does not affect it's throw direction. I would love to be able to sort this problem at the same time.


Here is my code from the tutorial, made to work in Unity 5


I am not a particularly good programmer or anything so please break it down for a newbie if you don't mind. Also some explanation of why it works would be awesome so that I can acctually learn from it and apply the concepts in other projects down the road without having to make a forum post everytime I get stuck.


The goal is to be able to pick up an object with a rigidbody (and hopefully make it static in relation to my player while holding it) and throw it in the direction I am facing.


Thanks for any help in advance.

using UnityEngine;
using System.Collections;

public class GrabandDrop : MonoBehaviour {
	GameObject grabbedObject;
	float grabbedObjectSize;

	// Use this for initialization
	void Start () {

	GameObject GetMouseHoverObject(float range){

		//Check for Collider with Raycast
		Vector3 position = gameObject.transform.position;
		RaycastHit raycastHit;
		Vector3 target = position + Camera.main.transform.forward * range;
		if (Physics.Linecast(position, target, out raycastHit ))
			return raycastHit.collider.gameObject;
		return null;

	void TryGrabbedObject(GameObject grabObject){

		//Check for Object if not null Grab it
		if (grabObject == null || !CanGrab(grabObject))
		grabbedObject = grabObject;
		grabbedObjectSize = grabObject.GetComponent<Renderer>().bounds.size.magnitude;

	//Can grab condition (RigidBody)
	bool CanGrab(GameObject candidate){
		return candidate.GetComponent<Rigidbody> () != null; 


	void DropObject(){

        //Release Direction and Velocity
        //Set multiplier larger for more force
        grabbedObject.GetComponent<Rigidbody> ().velocity = Vector3.forward * 50;

        //Check if hands are empty
        if (grabbedObject = null)
		//if holding object
		if (grabbedObject.GetComponent<Rigidbody> () != null)
			//stop object before release
			grabbedObject.GetComponent<Rigidbody> ().velocity = Vector3.zero;


	// UPDATE is called once per frame
	void Update () {
		//Assign Input for Grab
		if (Input.GetMouseButtonDown (1)) {

			if (grabbedObject == null)
				TryGrabbedObject (GetMouseHoverObject (5));
			//Set Grab and Drop as Same button (Right Mouse Button)
			else DropObject ();

		if (grabbedObject != null) {
			//Set position of grabbed Object after grabbing
			Vector3 newposition = gameObject.transform.position + Camera.main.transform.forward * grabbedObjectSize;
			grabbedObject.transform.position = newposition;


		Debug.Log (GetMouseHoverObject (5));


Share this post

Link to post
Share on other sites

In unity you can rotate vectors with a quaternion multiplication.
There're also direction vectors, those vectors are representations of relative coordinates to the center of your object. 

Let's say you want to throw something to the right:

1) Transform.rotation.quaternion*vector(1,0,0) (or you can use transform.right). (I can't recall if it was vector*quaternion or backwards)
2) This will be the first step to your velocity vector, you can add magnitude if you multiply it with a float. 

Edited by RenzoCoppola

Share this post

Link to post
Share on other sites

Ah so that might explain why one of my solutions didn't work.  I was thinking it projected from the "front face" of the object (set by the direction of pickup) instead of the center of the object but I am still not sure when or how it determines the initial rotation.

I never really understood what that quaternions entail either even though I have scoured the unity docs and tried to make sense of the definition on wikipedia. One of my attempts used quaternion but I can't figure out how they work in the code.  Is there any chance you could provide a generic example of how to manipulate them on a game object?

Share this post

Link to post
Share on other sites

Imagine that quaternion multiplications are like applying a rotation (that means that quat1*quat2 isn't like quat2*quat1). You might get into the analytical stuff sooner or later, but you are ready to go over this problem. 

Edited by RenzoCoppola

Share this post

Link to post
Share on other sites

I might add that when I said "center of your object", I was somehow wrong. When you talk about these "direction vectors" the object is always at (0,0,0). 

Share this post

Link to post
Share on other sites

Maybe I am missing something but I have applied them at pickup and at throw and neither one actually does anything noticeable to the object.  Is there something I am missing? Is a parent/child thing? Do I set it or read it in?  Does it inherit the parent's position? Maybe something to do with rigidbodies?  Is it possible that my coding practices are shit?  I make 3d models and and such and can rig, animate, etc but the programming aspect is the achilles heel that keeps most of my games from ever being published.  Is there some fundamental concept that I obviously do not posses?  If there is such a thing I cannot find it on google or youtube?


ANyway, no matter when or where I apply the rotation tt seems it is always the rotation on the object's origin instead of it's current position/rotation. The few times I can make a noticeable difference it is always on some sort of skewed plane I didn't declare.  I know this problem should be an easy one but this is essentially the core mechanic of my game and though I have gone through countless iterations of solutions of the problem the real fix still eludes me. And last time I decided to try everything I broke something I couldn't fix even after deleting all of the scripts.  ANd I feel like trying new stuff is going to result in the same thing, me remaking the whole thing from scratch.The large majority of my game is ready for alpha testing but without this mechanic it is all for naught.  The weird thing is that I have been working on a multitude of scripts for the various mechanics and this is the ONLY one that refuses to cooperate. I am at my wits end here and am seriously  considering abandoning the game at this point.  Partially because of frustration but also because I have spent weeks on a part of the game I can't get to work and changing that part of the game means changing the whole thing, which I just can't do.  Either I finish this thing or give up and I am not sure how  I can continue trying to make games when I spend too much time trying to do it already.

Share this post

Link to post
Share on other sites

Difficult stuff the first time. You need to make sure that you are using the correct components.

Let's say that you have your script in the throwable item. 
You know your camera/shoot direction transform. You take your  Transform.Forward from that transform, you multiplcate by speed, and then you modifiy the RigidBody.Velocity vector directly (the rigidbody from your throwable). 

Edited by RenzoCoppola

Share this post

Link to post
Share on other sites

Not sure if a typo or something, but line 49 looks like you're setting grabbed object to null, rather than testing?


also line 45 you have :


grabbedObject.GetComponent<Rigidbody> ().velocity = Vector3.forward * 50;


when you _probably_ want something like :


grabbedObject.GetComponent<Rigidbody> ().velocity = grabbedObject.transform.forward * 50;


as your update code looks to be already setting the position/rotation of the object.

Share this post

Link to post
Share on other sites

So I tried using the transform.forward and at least now it can leave my hands at something other than the same direction every time, which is good.  But the problem still seems to be that it takes "forward" as a particular face on the object, in my case it seems to be the one that is facing "up" on the cube. When it rotates in my hand it keeps that face as forward but it is always spinning and I can't stop the rotation from in game aside from setting it down and picking it up again. I think the solution would be to set the rotation on pickup and lock it until I throw it but I still can't figure out how to implement that.  I know this is probably simple for some people but I am new to programming and though I understand some of the the basic concepts I am still having a hard time figuring out how to manipulate functions of objects and such and getting the results I expect from them.

Share this post

Link to post
Share on other sites

Finally figured it out.


I needed to set the rotation of the picked object like this:

var newRot = gameObject.GetComponent<Rigidbody> ().transform.rotation;
            grabbedObject.transform.rotation = newRot;

Really wish it wouldn't have taken me a week and a broken game to figure it out though.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement