Unity2D移动变换触摸

时间:2015-08-17 09:56:31

标签: unity3d touch transform

当用户移动鼠标(在PC上)或手指(在移动设备上)时,我想移动我的主播放器 enter image description here

我做了一个简单的插图。如果我将手指向左移动10个单位,我希望玩家向左移动10个单位。对于手机和PC,我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:6)

<CheckBox Name="checkbox" Margin="141,148,336,147"/>

<Button Foreground="Black" Height="50" Margin="238,206,179,64">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <StackPanel Orientation="Horizontal">
                <Image>
                    <Image.Style>
                        <Style>
                            <Setter Property="Image.Source" 
                        Value="Images/cancel_16.ico" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding ElementName=checkbox, Path=IsChecked, 
                             RelativeSource={RelativeSource AncestorType=
                            {x:Type Button}}}" Value="True">
                                    <Setter Property="Image.Source" 
                                Value="Images/cancel_16grayscale.ico" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Image.Style>
                </Image>
                <ContentPresenter Content="{TemplateBinding Content}" 
            Margin="5,0,0,0" />
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>

将此代码添加到播放机的脚本中。

编辑:此代码很简单,可以将其转换为&#34;通过点击从每个地方移动&#34;。唯一的问题是OnMouse *函数只有在单击脚本和碰撞对象时才有效。只需使用Input.GetMouseButton更改它并解决它。

Vector3 screenPoint;
Vector3 offset;

void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

void OnMouseDrag()
{
    Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    transform.position = curPosition;
}

答案 1 :(得分:1)

你需要两个函数:DragStart(),你可以在每个鼠标按下时调用它们,以及Drag(),每当鼠标停留时调用它。

DragStart()方法中,您希望首先将鼠标位置捕获到名为“Vector2 mouseDown”的变量中,将另一个对象定位到名为Vector2 objectStart的变量中。

Drag()函数中,您创建了一个名为Vector2 offset的变量,基本上您只需offset = mouseDown - Input.mousePosition;来获取偏移量,现在您只需移动另一个对象即可金额作为您的抵消额:objectToMove.transform.localPosition = objectStart + offset