沿着Y轴移动玩家
本文关键字:玩家 移动 沿着 | 更新日期: 2023-09-27 18:10:09
我最近已经从SpriteKit和Swift转向Unity,并且我已经开始了一个Android项目。我想要的是只沿着Y方向上下移动玩家。在xcode中,我只需这样做:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let action = SKAction.moveToY(location.y, duration: 0.7)
action.timingMode = .EaseInEaseOut
player.runAction(action)
}
}
这种类型的代码会以同样的方式转换为c#吗?或者它的工作方式不同。
** UPDATE **
这是我用下面的答案之一尝试的代码,但玩家正在消失而不是移动,有什么建议吗?我所追求的是让玩家移动到点击屏幕的地方,但只能在Y轴上。谢谢:)
Vector2 touchPosition;
[SerializeField] float speed = 1f;
void Update() {
for (var i = 0; i < Input.touchCount; i++) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// assign new position to where finger was pressed
transform.position = new Vector3 (transform.position.x, Input.GetTouch(i).position.y, transform.position.z);
}
}
}
你可以通过调用transform.Translate()来移动场景中的任何对象,或者通过引用另一个对象的transform并调用Translate()。
基于手指移动移动当前脚本的场景对象
Vector2 touchDeltaPosition;
[SerializeField] float speed = 1f;
void Update() {
for (var i = 0; i < Input.touchCount; i++) {
if (Input.GetTouch(i).phase == TouchPhase.Moved) {
// get new finger position
touchDeltaPosition = Input.GetTouch(i).deltaPosition;
// move scene object along y axis
transform.Translate(0f, -touchDeltaPosition.y * speed, 0f);
}
}
}
移动当前脚本的场景对象到手指按压位置
void Update() {
for (var i = 0; i < Input.touchCount; i++) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
// assign new position to where finger was pressed
transform.position = new Vector3 (transform.position.x, Input.GetTouch(i).position.y, transform.position.z);
}
}
}
public float speed = 5.0f;
public void Update()
{
Vector3 moveDelta = new Vector3(0f, Input.GetAxis("Vertical"), 0f);
transform.Translate(moveDelta * speed * Time.deltatime)
}
对于那些需要知道的人来说,这是我的工作方式:
public GameObject;
public float smooth = 2;
private Vector3 _endPosition;
private Vector3 _startPosition;
private void Awake()
{
_startPosition = thingToMove.transform.position;
}
private void Update()
{
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
_endPosition = HandleTouchInput();
}
else
{
_endPosition = HandleMouseInput();
}
thingToMove.transform.position = Vector3.Lerp(thingToMove.transform.position, new Vector3(transform.position.x, _endPosition.y, 0), Time.deltaTime * smooth);
}
private Vector3 HandleTouchInput()
{
for (var i = 0; i < Input.touchCount; i++)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
var screenPosition = Input.GetTouch(i).position;
_startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
}
}
return _startPosition;
}
private Vector3 HandleMouseInput()
{
if(Input.GetMouseButtonDown(0))
{
var screenPosition = Input.mousePosition;
_startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
}
return _startPosition;
}
使用. lerp平滑地将对象移动到触摸位置。更多信息:http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html