- Home /
Place object relative to player location
Firstly I'd just like to say that this community so far has been invaluable to me!
Secondly the question, I'm trying to place an object (at the moment a cube) into the world via a keypress. I know the key press is all functional and everything, and I can place the object fine. I'm just not sure how to transform the object location to say 4 blocks infront of the player. I've been reading the transform.position help and to be honest I'm just not sure how to apply it.
Just to give as much info as I can, the script for this key input is on the player object which is called surprisingly "player". At the moment the cube is placed directly on top of the player. I can see that you can create objects at certain locations but I'm just not sure how to get the player's location, store that as a variable, then do object location = player.x + 4 in a sense.
Thanks! :)
private string message = "";
public Transform building;
void Update()
{
if (Input.GetKeyDown("h")) // You must use 'Input' only at the 'Update' functions
{
if(variablesResources.GetWood() >= 3)
{
message = "YOU BUILT A HOUSE";
variablesResources.SetWood(-3);
Invoke("HideMessage", 3);
var house = Instantiate(building, transform.position, transform.rotation);
}
else
{
message = "YOU DONT HAVE ENOUGH WOOD";
Invoke("HideMessage", 3);
}
}
}
void HideMessage()
{
message = "";
}
void OnGUI() // Is not static and you should not be making it so
{
GUI.Label(new Rect(50, 50, 300, 20), message);
}
}
wow does this even make a building?
as it's
public Transform building;
if not change Transform in to GameObject
well I don't know if it does but I use GameObject for this kind of stuff
jesus christ i just realised I've had a snipped of javascript and it works perfectly what is even with my life right now
Answer by whebert · Apr 08, 2013 at 04:59 PM
var
is valid C#, since C# 3.0 I think.
Anyway, if you always want to instantiate the object some distance in front of your current location, this would do the trick (using 4 as distance).
float distance = 4.0f;
Instantiate(building, transform.position + transform.forward*distance, transform.rotation);
worked just as I needed :D I should probably start using variables more often so I'll use that float definitely
Your answer
Follow this Question
Related Questions
Changing Mesh and Mesh Collider of an Object 0 Answers
Make object visible only for camera "X" 1 Answer
Location and rotation relative to another location and rotation 0 Answers
How to have the Player place GameObjects in scene at runtime? 3 Answers
Having a particle effect stick to player 0 Answers