从Unity中的另一个脚本访问对象的位置 [英] Accessing object's position from another script in Unity
问题描述
我正在做一个既有球又有球员的比赛.到目前为止,我为球制作了一个球体,为球员制作了一个正方形(稍后会制作模型).我将运动脚本附加到玩家上,以便可以向各个方向移动,但是我希望他在遇到球时能够捡起球.为此,我假设在球形脚本中的碰撞函数中,我必须将其位置更改为玩家的位置.所以我想知道:从球脚本访问球员的那些坐标的正确方法是什么?
I'm making a game with both a ball and a player. So far I made a sphere for the ball and a square (models will be made later) for the player. I attached a movement script to the player so that it can go in all directions, but I want him to be able to pick up the ball when he runs into it. To do this, I'm assuming that in the ball script, within a collision function, I would have to change its position to the position of the player. So I'm wondering: what is the correct way of accessing those coordinates of the player from the ball script?
推荐答案
我希望我理解正确.要获得该职位,您应该这样做:
I hope I understood you right. To just get the position you would do:
GameObject player = GameObject.Find ("Player");
Transform playerTransform = player.transform;
// get player position
Vector3 position = playerTransform.position;
但是要捡起并带走球,您应该宁愿做父母:
But to pick up and carry away the ball you should rather do parenting:
// ...
transform.parent = playerTransform;
// take care to disable physics while ball is under control of the player
rigidbody.isKinematic = true;
这样,您不必在每次更新或固定更新时都自己动球.如果玩家稍后放开球,则相反的方法是设置球的 transform.parent = null
和 isKinematic = false
.
This way you don's have to care about moving the ball by yourself every Update or FixedUpdate. If the player looses the ball later on, just reverse is by setting the ball's transform.parent = null
and isKinematic = false
.
这篇关于从Unity中的另一个脚本访问对象的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!