//
// DirectionView.swift
// SnakeGame
//
// Created by meininghuang on 2018/1/6.
// Copyright © 2018年 AppTest. All rights reserved.
//
import UIKit
importSnapKit
classDirectionView:UIView{
varbgView:UIView!
vartagView:UIView!
privatevartagViewCenterX:Constraint!
privatevartagViewCenterY:Constraint!
overrideinit(frame:CGRect) {
super.init(frame: frame)
self._setup()
}
requiredinit?(coder aDecoder:NSCoder) {
super.init(coder: aDecoder)
self._setup()
}
func_setup() {
letbgView =UIView()
self.addSubview(bgView)
bgView.backgroundColor=UIColor(white:0, alpha:0.4)
bgView.layer.shadowColor = UIColor.black.cgColor
bgView.layer.shadowOpacity=0.8
bgView.layer.shadowRadius=4
bgView.layer.shadowOffset=CGSize(width:4, height:4)
bgView.snp.makeConstraints{ (make)in
make.center.equalToSuperview()
make.left.top.equalTo(20)
}
self.bgView= bgView
lettagView =UIView()
self.addSubview(tagView)
tagView.backgroundColor=UIColor(white:0, alpha:0.8)
tagView.clipsToBounds=false
tagView.layer.cornerRadius=20
tagView.snp.makeConstraints{ (make)in
make.width.height.equalTo(40)
self.tagViewCenterX = make.centerX.equalToSuperview().constraint
self.tagViewCenterY = make.centerY.equalToSuperview().constraint
}
self.tagView= tagView
}
overridefunclayoutSubviews() {
super.layoutSubviews()
self.bgView.layer.cornerRadius = self.bgView.frame.size.height / 2.0
}
funcmove(_point:CGPoint) {
lethalf =self.bgView.frame.width/2
varx = point.x- half
vary = point.y- half
letA =atan(x / y)
letc =sqrt(pow(x,2) +pow(y,2))
ifc > half {
leta =sin(A) * half
letb =cos(A) * half
ify >0{
x = a
y = b
}else{
x = -a
y = -b
}
}
self.tagViewCenterX.update(offset: x)
self.tagViewCenterY.update(offset: y)
UIView.animate(withDuration:0.1) {
self.layoutIfNeeded()
}
}
overridefunctouchesBegan(_touches:Set, with event:UIEvent?) {
ifletpoint = touches.first?.location(in:self.bgView) {
self.move(point)
}
}
overridefunctouchesMoved(_touches:Set, with event:UIEvent?) {
ifletpoint = touches.first?.location(in:self.bgView) {
self.move(point)
}
}
overridefunctouchesEnded(_touches:Set, with event:UIEvent?) {
self.tagViewCenterX.update(offset: 0)
self.tagViewCenterY.update(offset: 0)
}
overridefunctouchesCancelled(_touches:Set, with event:UIEvent?) {
self.tagViewCenterX.update(offset: 0)
self.tagViewCenterY.update(offset: 0)
}
}