简体   繁体   English

在 Unity3D 中控制游戏对象时传送

[英]Teleport while Controlling GameObject in Unity3D

I am a freshman design student and they've asked us to create a game on unity3D without much training on it so needless to say I don't know much except for the super basic stuff.我是一名大一设计专业的学生,他们要求我们在没有太多培训的情况下在 unity3D 上创建一个游戏,所以不用说,除了超级基本的东西,我知道的不多。 I don't know anything about c# and I've been having an issue making a gameobject teleport.我对 c# 一无所知,而且我在制作游戏对象传送时遇到了问题。 I've spent 6 hours searching for a solution online and the only conclusion I got to was that my object is probably having issues teleporting because of the way I am controlling it - something to do with the controller remembering the last position before the teleport and returning to it.我花了 6 个小时在网上寻找解决方案,我得到的唯一结论是我的 object 可能由于我控制它的方式而在传送方面存在问题 - 这与 controller 记住最后一个 Z4757FE07FD492A8DBEDDEA6 之前的 Z4757FE07FD492A8DBEDDEA6 和 7回到它。 I have no idea how to fix it though.我不知道如何解决它。 So this is what my scene looks like: I have a sphere as my character, I move it to this other object that has a collider as trigger which then teleports my sphere to a different point (black object) on the terrain.所以这就是我的场景的样子:我有一个球体作为我的角色,我将它移动到另一个 object,它有一个对撞机作为触发器,然后将我的球体传送到地形上的不同点(黑色物体)。 As soon as my object reaches there, it starts sliding back to the point where the teleport happened.一旦我的 object 到达那里,它就会开始滑回传送发生的位置。 I even tried edit > project settings > physics > auto sync transforms as many suggested that and it worked for them.我什至尝试了许多建议的编辑>项目设置>物理>自动同步转换,它对他们有用。

This is the code by which I control my player:这是我控制播放器的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyPlayer : MonoBehaviour
{
    public float speed = 1;
    public float spacing = 1;
    private Vector3 pos;


    // Use this for initialization
    void Awake()
    {
        pos = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
            pos.x += spacing;
        if (Input.GetKeyDown(KeyCode.S))
            pos.x -= spacing;
        if (Input.GetKeyDown(KeyCode.D))
            pos.z -= spacing;
        if (Input.GetKeyDown(KeyCode.A))
            pos.z += spacing;


        transform.position = Vector3.MoveTowards(transform.position, pos, speed * Time.deltaTime);

    }
}

and I also have a camera that follows the sphere using this code而且我还有一个使用此代码跟随球体的相机

using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

    public GameObject player;       //Public variable to store a reference to the player game object


    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start () 
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }
    
    // LateUpdate is called after Update each frame
    void LateUpdate () 
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}

and I have another code on the camera that makes me be able to look around using my mouse我在相机上有另一个代码,让我可以用鼠标环顾四周

 using UnityEngine;
 using System.Collections;
 public class FlyCamera : MonoBehaviour
 {
     /*
     Writen by Windexglow 11-13-10.  Use it, edit it, steal it I don't care.  
     Converted to C# 27-02-13 - no credit wanted.
     Simple flycam I made, since I couldn't find any others made public.  
     Made simple to use (drag and drop, done) for regular keyboard layout  
     wasd : basic movement
     shift : Makes camera accelerate
     space : Moves camera on X and Z axis only.  So camera doesn't gain any height*/
     float mainSpeed = 700.0f; //regular speed
     float shiftAdd = 950.0f; //multiplied by how long shift is held.  Basically running
     float maxShift = 2000.0f; //Maximum speed when holdin gshift
     float camSens = 0.25f; //How sensitive it with mouse
     private Vector3 lastMouse = new Vector3(255, 255, 255); //kind of in the middle of the screen, rather than at the top (play)
     private float totalRun = 1.0f;
     void Update()
     {
         lastMouse = Input.mousePosition - lastMouse;
         lastMouse = new Vector3(-lastMouse.y * camSens, lastMouse.x * camSens, 0);
         lastMouse = new Vector3(transform.eulerAngles.x + lastMouse.x, transform.eulerAngles.y + lastMouse.y, 0);
         transform.eulerAngles = lastMouse;
         lastMouse = Input.mousePosition;
         //Mouse  camera angle done.  
         //Keyboard commands
         float f = 0.0f;
         Vector3 p = GetBaseInput();
         if (Input.GetKey(KeyCode.LeftShift))
         {
             totalRun += Time.deltaTime;
             p = p * totalRun * shiftAdd;
             p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
             p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
             p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
         }
         else
         {
             totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
             p = p * mainSpeed;
         }
         p = p * Time.deltaTime;
         Vector3 newPosition = transform.position;
         if (Input.GetKey(KeyCode.Space))
         { //If player wants to move on X and Z axis only
             transform.Translate(p);
             newPosition.x = transform.position.x;
             newPosition.z = transform.position.z;
             transform.position = newPosition;
         }
         else
         {
             transform.Translate(p);
         }
     }
     private Vector3 GetBaseInput()
     { //returns the basic values, if it's 0 than it's not active.
         Vector3 p_Velocity = new Vector3();
         if (Input.GetKey(KeyCode.W))
         {
             p_Velocity += new Vector3(0, 0, 1);
         }
         if (Input.GetKey(KeyCode.S))
         {
             p_Velocity += new Vector3(0, 0, -1);
         }
         if (Input.GetKey(KeyCode.A))
         {
             p_Velocity += new Vector3(-1, 0, 0);
         }
         if (Input.GetKey(KeyCode.D))
         {
             p_Velocity += new Vector3(1, 0, 0);
         }
         return p_Velocity;
     }
 }

Please let me know if there's a specific part of my code that I need to edit to resolve this or alternatively if you have a different code that won't give me this issue, that would make my life so much easier.如果我需要编辑代码的特定部分来解决这个问题,或者如果你有一个不会给我这个问题的不同代码,请告诉我,这会让我的生活变得更轻松。 If I need to edit something or you're sharing a code, please respond with the complete (corrected) code because otherwise I will just be even more confused.如果我需要编辑某些内容或者您正在共享代码,请回复完整(更正)的代码,否则我会更加困惑。

I know this is a super long post and I am sorry but I am really desperate.我知道这是一个超长的帖子,我很抱歉,但我真的很绝望。 It's been really hard studying online and basically having to teach myself all of this.在网上学习真的很辛苦,而且基本上必须自学所有这些。 This is for a final project so I will really appreciate any help you can throw my way.这是一个最终项目,因此我将非常感谢您提供的任何帮助。 Thank you for reading and thanks for any help in advance.感谢您阅读并提前感谢您的任何帮助。

EDIT: The teleport code is executing fine because I do teleport to the chosen location, I just end up sliding back to the point which I teleported from.编辑:传送代码执行得很好,因为我确实传送到了选定的位置,我最终只是滑回了我传送的点。

This is the teleporting code I am using.这是我正在使用的传送代码。

using UnityEngine;
using System.Collections;

public class Teleport : MonoBehaviour
{
    public GameObject ui;
    public GameObject objToTP;
    public Transform tpLoc;
    void Start()
    {
        ui.SetActive(false);
    }

    void OnTriggerStay(Collider other)
    {
        ui.SetActive(true);
        if ((other.gameObject.tag == "Player") && Input.GetKeyDown(KeyCode.E))
        {
            objToTP.transform.position = tpLoc.transform.position;
        }
    }
    void OnTriggerExit()
    {
        ui.SetActive(false);
    }
}

Ok, so the main reason why your character is drifting back to original position is that the pos variable in the MyPlayer script stays the same after teleporting.好的,所以你的角色回到原来的 position 的主要原因是MyPlayer脚本中的pos变量在传送后保持不变。

Remedy for that will be changing pos variable from Teleport script after objToTP.transform.position = tpLoc.transform.position;解决方法是在objToTP.transform.position = tpLoc.transform.position;之后从Teleport脚本更改pos变量; . . Something like objToTP.gameobject.GetComponent<MyPlayer>().pos = tpLoc.transform.position ;类似objToTP.gameobject.GetComponent<MyPlayer>().pos = tpLoc.transform.position

But make sure that objToTP has component MyPlayer and pos in MyPlayer is public.但请确保objToTP具有组件MyPlayer并且MyPlayer中的pos是公共的。

Once again: it's a simple way to resolve your problem.再一次:这是解决问题的简单方法。 In a real project you should create more flexible architecture, but that's a different story.在实际项目中,您应该创建更灵活的架构,但那是另一回事。

I believe that you sliding back because you moving player with transform.position = Vector3.MoveTowards in Update().我相信您会向后滑动,因为您在 Update() 中使用transform.position = Vector3.MoveTowards移动播放器。
And you moving it to coordinates that was got from your input然后将其移动到从输入中获得的坐标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM