'Can I make a character carry an object in Unity 2D?
This is probably a very simple question, but is it possible to make a character carry an object in Unity 2D? I can make an object move at the same speed as the player, and I can make the player object flip from side to side. However, when the player moves onto one side, the object that I want the player to be facing obviously does not move with it. I could not find much code for mirror imaging, so I first tried teleporting the character using the transform. position command like so:
if (stHorizontalInput > 0.01f)
{
float stHorizontalOutput1 = stHorizontalInput * spede * Time.deltaTime;
float stVerticalOutput1 = stVerticalInput * spede * Time.deltaTime;
while (stHorizontalOutput1 < 10f)
{
transform.position = transform.position + new Vector3(stHorizontalOutput1, stVerticalOutput1, 0);
}
}
However, this did in fact not work. At first, the object visibly moved, and quickly too, and I thought that a simple while loop would solve the issue of the object moving too far too fast, and way further than I needed it to, but with a while loop added as shown to prevent moving too far, the object would not move at all. I cannot make the object and the player one asset because the object needs to have a specific function that the player cannot.
Solution 1:[1]
Still learning more about unity, but I think from a scripting perspective you should be able to "attach" your object to your character with something like this.
GameObject specialObject;
GameObject Character;
void SomeFunction()
{
specialObject. transform. position
=
Character. transform. position;
}
You can play with the offsets to get it placed correctly on the hand. Might need a ifLeft == true or something to adjust the offset on flips.
This Unity learning guide talks about doing this with the camera. https://learn.unity.com/tutorial/1-3-make-the-camera-follow-the-vehicle-with-variables.
I imagine you can do very similar for your character and object in the 2D view.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |