简体   繁体   English

Unity 3D中用于水平射击者的角色控制器

[英]Character Controller for Horizontal Shooter in Unity 3D

I am creating a horizontal side-scrolling shooter which I plan to release on mobile devices. 我正在创建一个水平横向滚动射击游戏,计划在移动设备上发布。 How can I set up the ship so that: 我该如何设置飞船,以便:

  • It can be moved up/down/left/right freely (with varying horizontal/vertical speeds) 可以自由地向上/向下/向左/向右移动(水平/垂直速度变化)
  • Collide and stop against obstacles (ie IF collision with obstacle STOP) 碰撞并停止以避开障碍物(即如果与障碍物STOP发生碰撞)
  • Diagonal movement against horizontal plane (down + right input) should move right pressed against floor 相对于水平面的对角线移动(向下+向右输入)应向右压紧地板

The ship must not be able to pass through obstacles. 该船一定不能穿过障碍物。

I created a custom character controller which simply adjust position based on velocity. 我创建了一个自定义字符控制器,该控制器仅根据速度调整位置。 I cannot figure out how to detect collision and avoid moving through obstacles. 我无法弄清楚如何检测碰撞并避免穿过障碍物。 There must be an easier way to achieve this simple requirement. 必须有一种更简单的方法来实现这一简单要求。

Note: To clarify, the camera follows the ship, it does not automatically scroll. 注意:为清楚起见,相机会跟随船,它不会自动滚动。 The player can stop the ship by releasing input button. 玩家可以通过释放输入按钮来停止飞船。

To start with, try making sure you've added a collider component to your obstacles and to your character controller. 首先,请尝试确保已将对撞机组件添加到障碍物和角色控制器中。 That should be enough to stop your ship passing through the obstacles. 这足以阻止您的飞船越过障碍物。

I was storing my own velocity vector which I was then applying using transform.Translate . 我正在存储自己的velocity矢量,然后使用transform.Translate将其应用。 This obviously was ignoring any collision detection and would have required a custom collision detection implementation. 显然,这将忽略任何冲突检测,并且需要自定义冲突检测实现。

Instead I found that the Rigidbody component contains its own velocity variable. 相反,我发现Rigidbody组件包含其自己的velocity变量。 That velocity value can be easily altered and the object will automatically translate and collide with obstacles. 可以轻松更改该速度值,并且对象将自动平移并与障碍物碰撞。 Here is an example: 这是一个例子:

using UnityEngine;
using System.Collections;

public class CharacterController : MonoBehaviour {

    public Vector2 maximumSpeed = new Vector2(1.0f, 1.0f);

    void Start() {

    }

    void Update() {
        Rigidbody rigidbody = GetComponent<Rigidbody>();

        Vector2 velocity = new Vector2();

        velocity.x = Input.GetAxis("Horizontal") * maximumSpeed.x;
        velocity.y = Input.GetAxis("Vertical") * maximumSpeed.y;

        rigidbody.velocity = velocity;
    }

}

This appears to work quite well. 这似乎工作得很好。 Comments would be appreciated :-) 评论将不胜感激:-)

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

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